Leetcode 28. 找出字符串中第一个匹配项的下标
题目链接:28. 找出字符串中第一个匹配项的下标
思路:
在一个串中查找是否出现过另一个串 ➡ KMP算法。KMP算法很重要的一部分是实现next数组。
解题:失败
代码实现
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0; // needle为空的情况我没判断
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for(int i = 0; i < haystack.length(); i++){
while(j > 0 && haystack.charAt(i) != needle.charAt(j)){
j = next[j-1];
}
if(haystack.charAt(i) == needle.charAt(j)){
j++;
}
if(j == needle.length()){
return (i - needle.length() + 1);
}
}
return -1;
}
public void getNext(int[] next, String needle){
int j = 0;
next[0] = 0;
for(int i = 1; i < next.length; i++){
while(j > 0 && needle.charAt(j) != needle.charAt(i)){
j = next[j-1];
}
if(needle.charAt(j) == needle.charAt(i)){
j++;
}
next[i] = j;
}
}
}
时间复杂度:O(n+m)
空间复杂度:O(m)
Leetcode 459. 重复的子字符串
题目链接:459. 重复的子字符串
思路:
没思路。
解题:失败
代码实现
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n = s.length();
int[] next = new int[n];
getNext(next, s);
if(next[n - 1] != 0 && (n % (n - next[n-1]) == 0)){
return true;
}
return false;
}
public void getNext(int[] next, String s){
int j = 0;
next[0] = 0;
for(int i = 1; i < next.length; i++){
while(j > 0 && s.charAt(i) != s.charAt(j)){
j = next[j - 1];
}
if(s.charAt(i) == s.charAt(j)){
j++;
}
next[i] = j;
}
}
}
时间复杂度:O(n)
空间复杂度:O(n)
在由重复子串组成的字符串中,最长相等前后缀不包含的子串就是最小重复子串。
看完视频,并没有真正理解,为什么数组的长度正好可以被(数组长度-最长相等前后缀的长度)整除 ,说明该字符串有重复的子字符串。
总结
字符串:
- 双指针法
双指针法在数组,链表和字符串中很常用。 - 反转字符串
反转字符串;反转字符串中的单词;左/右旋 - KMP
使用KMP可以解决两类经典问题:(1)匹配问题;(2)重复子串问题