💡 解题思路
- 📝 确定输入与输出
- 🔍 分析复杂度
- 🔨 复杂题目拆分 :严谨且完整 地拆分为更小的可以解决的子问题(字符的逻辑拆分)–(多总结)
- 💭 选择处理逻辑: 根据拆分后的子问题,总结并选择合适的问题处理思路(拆分,拼接,KMP思想)
- 🔎 检查特殊情况:边界条件和特殊情况
- 🏁 返回结果
151.翻转字符串里的单词(字符串旋转拼接)
class Solution {public String reverseMessage(String message) {if (message == null || message == "") return new String(); String[] strs = message.split(" ");StringBuffer sb = new StringBuffer();int len = strs.length;for (int i = len - 1; i >= 0; i--) {if (!strs[i].isEmpty()) {sb.append(strs[i]);sb.append(" ");}}return sb.toString().trim();}
}
卡码网:55.右旋转字符串(字符串旋转拼接)
import java.util.Scanner;public class Main{public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int len = scanner.nextInt();String str = scanner.next();int length = str.length(), index = length - len;System.out.println(str.substring(index, length) + str.substring(0, index));}
}
28. 找出字符串中第一个匹配项的下标(KMP算法)
class Solution {public int strStr(String haystack, String needle) {int len = haystack.length(), lenn = needle.length();int[] next = getNext(needle);for (int i = 0, j = 0; i < len; i++) {while(j > 0 && haystack.charAt(i) != needle.charAt(j)) {j = next[j-1];}if (haystack.charAt(i) == needle.charAt(j)) {j++;}if (j == lenn) return i - lenn + 1;}return -1;}private int[] getNext(String needle) {int len = needle.length();int i = 0, j = 1;int[] next = new int[len];next[0] = 0;for (; j < len; j++) {while (i > 0 && needle.charAt(i) != needle.charAt(j)) {i = next[i-1];}if (needle.charAt(i) == needle.charAt(j)) {i++;}next[j] = i;}return next;}
}
459.重复的子字符串(KMP算法)
class Solution {public boolean repeatedSubstringPattern(String s) {return kmp(s+s, s);}private boolean kmp(String query, String pattern) {int len = pattern.length();int[] next = new int[len];for(int i = 1, j = 0; i < len; i++) {while(j > 0 && pattern.charAt(i) != pattern.charAt(j)) {j = next[j-1];}if (pattern.charAt(i) == pattern.charAt(j)) j++;next[i] = j;}for (int i = 1, j = 0; i < 2 * len - 1; i++) {while (j > 0 && query.charAt(i) != pattern.charAt(j)) {j = next[j-1];}if (pattern.charAt(j) == query.charAt(i)) {j++;if (j == len) return true;}}return false;}
}