您的位置:首页 > 其它

[leetcode] 28.Implement strStr()

2015-08-31 18:50 573 查看
题目:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: