您的位置:首页 > 其它

28.LeetCode Implement strStr()(meidum)[字符串 子串匹配]

2016-04-15 09:56 423 查看
Implement strStr().

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

Subscribe to see which companies asked this question
strStr(str1,str2)的功能是判断str2是否是str1的子串,解题思路如下:首先判断str2是否是空串,空串是任何字符串的子串返回0;当str2的长度大于str1的时候,那么str2肯定不是str1的子串,返回-1;str2从开始字串针对str1开始扫描,但是由于后面的子串需要完全匹配,所以对str1的扫描只需要扫描到<=str1.size()-str2.size()的地方为止。

class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size()>haystack.size()) return -1;
if(needle.size() == 0) return 0;
int pos = -1;
int i = 0;
for(int j=0;j<=haystack.size()-needle.size();j++)
{
if(haystack[j] == needle[i])
{
int p = i,q = j;
while(p<needle.size()&&q<haystack.size())
{
if(needle[p]!= haystack[q])
break;
else
{
++p;++q;
}
}
//cout<<p<<endl;
if(p == needle.size())
{
pos = j;
break;
}
}
}
return pos;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: