2020年7月8日 星期三

LeetCode 28. Implement strStr() [Easy] [C++] 解題筆記

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

EX:

        Input: haystack = "hello", needle = "ll"

        Output: 2
        Input: haystack = "aaaaa", needle = "bba"
        Output: -1
想法:
    這題沒啥特別的作法,直接暴力法以 haystack 的每個位置當開頭開始遍歷看看是否包含 needle。

完整程式碼:
class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.empty()) { return 0; }
        if (haystack.size() < needle.size()) { return -1; }
        if (haystack.size() == needle.size()) {
            return (haystack == needle)? 0 : -1;
        }
        for (int i = 0; i <= haystack.size() - needle.size(); i++) {
            if (haystack[i] == needle[0] && needle.size() == 1) { return i; }
            if (haystack[i] == needle[0]) {
                int j = 1;
	        for (j; j < needle.size(); j++) {
                    if (i + j >= haystack.size() || haystack[i + j] != needle[j]) { break; }     
		    //if (j == needle.size()-1) { return i; } 
                }
	        if (j == needle.size()) { return i; }
            }
        }
        return -1;       
    }
};

沒有留言:

張貼留言