1 题目:
28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
2 参考 :
28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)
3 代码:
C++
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
for (int i = 0; i + m <= n; i++) {
bool flag = true;
for (int j = 0; j < m; j++) {
if (haystack[i + j] != needle[j]) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
};
Python
# 暴力解决
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(0,len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
4 思路:
暴力解法,其他方法,整不会了。。。。。。