題目:
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;
}
};