28. Find the Index of the First Occurrence in a String
Link: https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
Description
Given two strings needle
and haystack
, return the index of the first occurrence of needle
in haystack
, or -1
if needle
is not part of haystack
.
Approach
KMP
Link: https://programmercarl.com/0028.%E5%AE%9E%E7%8E%B0strStr.html
Solution
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0)
return 0;
int[] next = new int[needle.length()];
getNext(needle, next);
int j = -1;
for (int i = 0; i < haystack.length(); i++) {
while (j >= 0 && haystack.charAt(i) != needle.charAt(j + 1))
j = next[j];
if (haystack.charAt(i) == needle.charAt(j + 1))
j++;
if (j == needle.length() - 1)
return i - (needle.length() - 1);
}
return -1;
}
private void getNext(String s, int[] next) {
int j = -1;
next[0] = -1;
for (int i = 1; i < s.length(); i++) {
while (j >= 0 && s.charAt(i) != s.charAt(j + 1))
j = next[j];
if (s.charAt(i) == s.charAt(j + 1))
j++;
next[i] = j;
}
}
}
459. Repeated Substring Pattern
Link: https://leetcode.com/problems/repeated-substring-pattern/
Description
Given a string s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Approach
KMP
Link: https://programmercarl.com/0459.%E9%87%8D%E5%A4%8D%E7%9A%84%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2.html
移动匹配
Link: https://programmercarl.com/0459.%E9%87%8D%E5%A4%8D%E7%9A%84%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2.html
Solution
class Solution {
public boolean repeatedSubstringPattern(String s) {
String s2 = s + s;
String s1 = s2.substring(1, s2.length() - 1);
System.out.println(s1);
if (s1.contains(s))
return true;
else
return false;
}
}
class Solution {
public boolean repeatedSubstringPattern(String s) {
if (s.length() == 0)
return false;
int[] next = new int[s.length()];
getNext(s, next);
for (int i: next)
System.out.println(i);
if (next[s.length() - 1] >= 0 && s.length() % (s.length() - (next[s.length() - 1] + 1)) == 0)
return true;
else
return false;
}
private void getNext(String s, int[] next) {
int j = -1;
next[0] = -1;
for (int i = 1; i < s.length(); i++) {
while (j >= 0 && s.charAt(i) != s.charAt(j + 1))
j = next[j];
if (s.charAt(i) == s.charAt(j + 1))
j++;
next[i] = j;
}
}
}