版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/86727226
这是一道比较简单的问题,就是找出母字符串中是否有与子字符串相匹配的字符串。
要注意的就是几点,题目中要求当needle串为空时,要返回0,没有匹配的则返回 -1.
下面是题目的具体描述,haystack代表长的,needle则代表短的。
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
int i,j;
if(m < n )
return -1;
if(n == 0)
return 0;
for(i = 0; i <= m-n ; i++)
{
for(j = 0; j < n; j++)
{
if(haystack[i+j] != needle[j])
{
break;
}
}
if(j == n)
return i;
}
return -1;
}
};