您的位置:首页 > 其它

[LeetCode]Implement strStr()

2015-11-03 16:27 309 查看
题目描述:(链接

Implement strStr().

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

解题思路:

class Solution {
public:
int strStr(string haystack, string needle) {
int sub_len = needle.size();
int total_len = haystack.size();
if (sub_len > total_len) {
return -1;
}

if (haystack == needle) {
return 0;
}

int result = -1;
for (int i = 0; i <= total_len - sub_len; ++i) {
if (haystack.substr(i, sub_len) == needle) {
result = i;
break;
}
}

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