28. Find the Index of the First Occurrence in a String
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
.
Example 1:
Input: haystack = “sadbutsad”, needle = “sad”
Output: 0
Explanation: “sad” occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = “leetcode”, needle = “leeto”
Output: -1
Explanation: “leeto” did not occur in “leetcode”, so we return -1.
class Solution {
public int strStr(String haystack, String needle) {
int haystackLength = haystack.length();
if (haystackLength == 0)return 0;
int needleLength = needle.length();
int[] next = findNext(needle);
int i = 0, j = 0;
while (i < haystackLength && j < needleLength){
if (j == -1 || haystack.charAt(i) == needle.charAt(j)){
i++;
j++;
} else {
j = next[j];
}
}
if (j == needleLength)return i-j;
else return -1;
}
public int[] findNext(String needle){
int length = needle.length();
//这里是+1,因为是反映此处没匹配上时前面应该挪到什么位置
int[] next = new int[length+1];
next[0] = -1;
int k = -1, j = 0;
while (j < length){
if (k == -1 || needle.charAt(k) == needle.charAt(j)){
k++;
j++;
next[j] = k;
}
else k = next[k];
}
return next;
}
}
心得:难度还行,学过稍微有点忘了,简单复习了一下写的
459. Repeated Substring Pattern
Given a string s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = “abab”
Output: true
Explanation: It is the substring “ab” twice.
Example 2:
Input: s = “aba”
Output: false
Example 3:
Input: s = “abcabcabcabc”
Output: true
Explanation: It is the substring “abc” four times or the substring “abcabc” twice.
class Solution {
public boolean repeatedSubstringPattern(String s) {
int length = s.length();
int[] next = getNext(s);
if (next[length] == 0)return false;
return length % (length - next[length]) == 0;
}
public int[] getNext(String s){
int length = s.length();
int[] next = new int[length+1];
int i = -1, j = 0;
next[0] = -1;
while (j < length){
if (i == -1 || s.charAt(i) == s.charAt(j)){
i++;
j++;
next[j] = i;
} else {
i = next[i];
}
}
return next;
}
}
心得:这题也挺难的,思路不太好想,本质思路也是使用KMP算法,看懂以后代码好写