题目
题解
这道题的名字起得很有意思,haystack是草垛,needle是针,意思是让你在草垛里找一根针
看到这道题,第一个想的是用数据结构时候学的KMP,但是KMP理解起来比较复杂,这道题也没有那么复杂,就用简单的双指针了
例如:haystack=“mississippi”,needle=“issip”
初始:i指针=0,指向’m’,j指针=1,指向’s’
先找“起点”:当i==1时,haystack[i]==needle[0],进入内循环
检查连续:在内循环中,当j==4时,haystack[i+j]是’s’,needle[j]是’p’,说明haystack的子串和needle不是连续相等。j置1,跳出内循环,i变成2,即下一次从mississippi开始
重复以上过程,直到退出内循环时 j==needle.size()时返回 i
不满足上述条件,即在haystack中找不到needle,则返回-1
C++
法1:双指针
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle=="")
return 0;
int i=0,j=1;//haystack,needle的指针
while(i<haystack.size())
{
//起点:找到haystack中与needle首字符相同的
if(haystack[i]==needle[0])
{
//检查连续:haystack中与needle相同的子串需要连续
while(j<needle.size())
{
//有一个不符,则从i+1再来
if(haystack[i+j]!=needle[j])
{
j=1;
break;
}
j++;
}
//haystack子串与needle完全一样,返回i
if(j==needle.size())
return i;
}
i++;
}
//找了一圈没找到,返回-1
return -1;
}
};
时间复杂度为O(n2),没有进行简化,第一次在leetcode上见执行用时这么长。。。
法2:库函数,就是知道一下,其实跟没写没什么区别
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle=="")
return 0;
int pos=haystack.find(needle);
return pos;
}
};
不愧是人家打包好的,执行用时一下变成4ms了
python
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle=="":
return 0
i=0
while i<len(haystack):
# 找到子串,返回i
if haystack[i:i+len(needle)]==needle:
return i
# 没找到,继续向后找
else:
i+=1
return -1
在python中用了一个 haystack[i:i+len(needle)]==needle
来表达,减少了一层内循环,使代码简洁了好多,执行用时也可以控制在两位数,时间复杂度O(n)