文章目录
28.找出字符串中第一个匹配项的下标
题目
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
示例1:
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例2:
输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104
haystack
和needle
仅由小写英文字符组成
c++ 代码实现
class Solution {
public:
void getNext(vector<int>& next, string needle) {
int j = 0;
// 注意从 1 开始
for (int i = 1; i < needle.size(); i++) {
while (j > 0 && needle[i] != needle[j]) {
j = next[j-1];
}
// 相同
if (needle[i] == needle[j]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
if (n < 1) return 0;
vector<int> next(n);
getNext(next, needle);
int j = 0;
for (int i = 0; i < m; i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = next[j-1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == n) {
return (i - n + 1);
}
}
return -1;
}
};
python代码实现
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
haystackList = list(haystack)
needleList = list(needle)
m = len(haystackList)
n = len(needleList)
if n < 1:
return 0
j = 0
net = [0] * n
for i in range(1, n):
while j > 0 and needleList[i] != needleList[j]:
j = net[j-1]
if (needleList[i] == needleList[j]):
j += 1
net[i] = j
j = 0
for i in range(m):
while j > 0 and haystackList[i] != needleList[j]:
j = net[j-1]
if (haystackList[i] == needle[j]):
j+=1
if (j == n):
return (i-n+1)
return -1
459.重复的子字符串
题目:
给定一个非空的字符串 s
,检查是否可以通过由它的一个子串重复多次构成。
示例1:
输入: s = "abab"
输出: true
解释: 可由子串 "ab" 重复两次构成。
示例2:
输入: s = "aba"
输出: false
示例3:
输入: s = "abcabcabcabc"
输出: true
解释: 可由子串 "abc" 重复四次构成。 (或子串 "abcabc" 重复两次构成。)
c++ 代码实现
class Solution {
public:
void getNext(vector<int>& next, string s) {
int j = 0;
for (int i = 1; i < s.size(); i++) {
while (j > 0 && s[i] != s[j]) {
j = next[j-1];
}
if (s[i] == s[j]) {
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
int m = s.size();
if (m == 0) return false;
vector<int> next(m);
getNext(next, s);
if ( next[m-1] != 0 && m % (m - next[m - 1]) == 0 ) {
return true;
}
return false;
}
};
python 代码实现
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
sList = list(s)
m = len(sList)
if m == 0:
return False
nxt = [0] * m
j = 0
for i in range(1, m):
while j > 0 and sList[i] != sList[j]:
j = nxt[j-1]
if (sList[i] == sList[j]):
j += 1
nxt[i] = j
if nxt[m-1] != 0 and m % (m - nxt[m-1]) == 0:
return True
return False