题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
实现strstr(),找到子串在原串中出现的第一个下标。
代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty())return 0;
else if(haystack.empty())return -1;
int needleSize = needle.length();
int haystackSize = haystack.length();
for (int i = 0; i <= haystackSize - needleSize; i++) {
int j = 0;
for (; j < needleSize; j++) {
if (haystack[i + j] != needle[j])break;
}
if (j == needleSize)return i;
}
return -1;
}
};