问题描述

Implement strStr().

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

思路

直接遍历haystack,然后一个一个字符去与needle匹配,完全匹配则成功;失败则迭代到下一字符,直到haystack.length - needle.length为止。

代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.length();
		int n = needle.length();
		if(n<=0)  {
			return 0;
		}
		int index = -1;
		for(int i=0;i<=m-n;i++) {
			int pos = i;
			for(int j=0;j<n;j++) {
				if(haystack[pos]==needle[j]&&index==-1) {
					index = i;
				} else if(haystack[pos]!=needle[j]){
					index = -1;
					break;
				}
				pos++;
			}
			if(index!=-1) break;
		}
		return index; 
    }
};