leetcode-28-implement strstr()

Problem Description:

Implement strStr().

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

题目大意:

返回字符串中某子串的出现的第一个序列号。

Solutions:

维护一个长度和子串相等的滑动窗口,比较它是否和子串相等即可。

Code in C++:

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.length()>haystack.size()) return -1;
        if(needle=="") return 0;
        for(int i = 0 ; i <haystack.length();i++)
        {
            string win= haystack.substr(i,needle.size());
            if(win==needle) return i;
        }
        return -1;

    }
};