28. Implement strStr()

description:

mplement strStr().

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

Example:

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

my answer:

感恩

my answer:

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.size() == 0) return 0;
        if(haystack.size() < needle.size()) return -1;//这里所有的特殊情况都要考虑周全,刚开始就没想到
        for(int i = 0; i <= haystack.size() - needle.size() ; i++){
            //这里注意i的循环范围,其中有一个测试是两个字符串都是一大长串的aaaaaaa长到一个一个比就oom了,但是其实他们相差的不是很多
            for(int j = 0; j < needle.size(); j++){
                if(needle[j] == haystack[i+j] && j == needle.size() - 1){
                    return i;
                }
                if(needle[j]!= haystack[i+j])break;
            }
        }
        return -1;
    }
};

relative point get√:

hint :

原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11063132.html