提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣151. 反转字符串中的单词
- 二、力扣55. 右旋字符串(第八期模拟笔试)
- 三、力扣28. 找出字符串中第一个匹配项的下标
前言
KMP主要应用在字符串匹配上。 KMP的主要思想是当出现字符串不匹配时,可以知道一部分之前已经匹配的文本内容,可以利用这些信息避免从头再去做匹配了。
一、力扣151. 反转字符串中的单词
class Solution {public String reverseWords(String s) {StringBuilder sb = new StringBuilder();StringBuilder bb = new StringBuilder();char[] ch = s.toCharArray();for(int i = 0; i < ch.length; i ++){if(ch[i] != ' '){bb.append(ch[i]);}else if(i > 0 && ch[i] == ' ' && ch[i-1] != ' '){bb.reverse();sb.append(bb.toString()).append(' ');bb = new StringBuilder();}else{continue;}}if(bb.length() > 0){sb.append(bb.reverse().toString());}else{sb.deleteCharAt(sb.length()-1);}sb.reverse();return sb.toString();}
}
二、力扣55. 右旋字符串(第八期模拟笔试)
class M{public String fun(String s, int k){if(k >= s.length()){return s;}char[] ch = s.toCharArray();int n = s.length();ch = f(ch,0,k-1);ch = f(ch,k,n-1);ch = f(ch,0,n-1);retun new String(ch);}public char[] f(char[] ch,int low, int high){for(int i = low, j = high; i <j; i ++, j --){char temp = ch[i];ch[i] = ch[j];ch[j] = temp;}return ch;}public static void main(){Scanner scan = new Scanner(System.in);int k = scan.nextInt();String s = scan.next();System.out.System.out.println(fun(s,k);}
}
三、力扣28. 找出字符串中第一个匹配项的下标
class Solution {public int strStr(String haystack, String needle) {int res = -1;char[] ch1 = haystack.toCharArray();char[] ch2 = needle.toCharArray();int i = 0, j = 0;for(;i < ch1.length && j < ch2.length; ){if(ch1[i] == ch2[j]){i ++;j ++;}else{i = i-j+1;j = 0;}if(j == ch2.length){res = i-j;}}return res;}
}