1.力扣344-反转字符串
第一个和倒数第一个交换,第二个和倒数第二个交换
class Solution {
public void reverseString(char[] s) {
for(int i = 0, j = s.length - 1; i < j; i ++, j --){
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
2.力扣541-反转字符串2
class Solution {
public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
for(int i = 0; i < s.length(); i += 2 * k){
int start = i;
int end = Math.min(s.length() - 1, start + k - 1);
while(start < end){
char c = ch[start];
ch[start] = ch[end];
ch[end] = c;
start ++;
end --;
}
}
return new String(ch);
}
}
3.力扣28-找出字符串中第一个匹配项的下标(KMP算法)
!!!最主要的就是找到最长相等前后缀,前缀表
class Solution {
public int strStr(String haystack, String needle) {
int[] next = new int[needle.length() + 1];
for(int j = 2, i = 0; j <= needle.length(); j ++){
while(i > 0 && needle.charAt(i) != needle.charAt(j - 1)) i = next[i];
if(needle.charAt(i) == needle.charAt(j - 1)) i ++;
next[j] = i;
}
for(int i = 0, j = 0; i < haystack.length(); i ++){
while(j > 0 && haystack.charAt(i) != needle.charAt(j)) j = next[j];
if(haystack.charAt(i) == needle.charAt(j)) j ++;
if(j == needle.length()){
return i - j + 1;
}
}
return -1;
}
}
4.力扣459-重复的子字符串-kmp算法
class Solution {
public boolean repeatedSubstringPattern(String s) {
int l = s.length();
int[] next = new int[l + 1];
for(int i = 0, j = 2; j <= l; j ++){
while(i > 0 && s.charAt(i) != s.charAt(j - 1)) i = next[i];
if(s.charAt(i) == s.charAt(j - 1)) i ++;
next[j] = i;
}
if(next[l] > 0 && l % (l - next[l]) == 0) return true;
else return false;
}
}
标签:ch,charAt,int,needle,next,length,字符串
From: https://www.cnblogs.com/wusuoweiju/p/17978454