您的位置:首页 > 其它

Leetcode 28. Implement strStr()

2018-01-02 11:13 429 查看
题目的意思是判断needle是否是haystack的子串,如果不是的话就返回-1,如果是的话就返回haystack中与needle匹配的子串的第一个字符的索引值。

 

方法1:遍历haystack,遇到与needle[0]相等的字符,就判断两个字符串接下来的needle.size()-1个字符是否匹配,匹配的话就返回haystack中第一个匹配字符的索引值。

class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0; ; ++i)
{
for (int j = 0; ; ++j)
{
if (j == needle.size())
return i;
if(i+j==haystack.size())
return -1;
if (haystack[j + i] != needle[j])
break;
}
}
}
};


方法2:用了substr。

class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
for(int i=0; i<haystack.size(); i++)
{
if(haystack.substr(i,needle.size())==needle)
return i;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode