标签:
代码:
这道题提醒我一点,要主要修剪多余的计算。
第一个for循环,结束位置是m-n+1 而不是m。
第二个for循环,用break也是避免多余计算。
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if (n == 0) return 0;
for (int i = 0; i < m - n + 1; i++) { // pointer of starting position
int j = 0;
for (; j < n; j++) // pointer checking unifomity
if (haystack[i + j] != needle[j])
break;
if (j == n) return i;
}
return -1;
}
};
Leetcode 28. Implement strStr()
标签:
原文地址:http://www.cnblogs.com/casperwin/p/5751184.html