class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(needle)
for i in range(len(haystack)-m+1):
if haystack[i:i+m] == needle:
return i
return -1
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(),m=needle.size();
for(int i=0;i<n-m+1;i++){
if(haystack.substr(i,m)==needle) return i;
}
return -1;
}
};
c++中,s.substr(i,x)//截取从下标i开始,长度为x的字符串
或者用find()函数
class Solution {
public:
int strStr(string haystack, string needle) {
return pos=haystack.find(needle);
}
};
28. 实现 strStr()-力扣
最新推荐文章于 2024-11-05 10:53:19 发布