💡 解题思路
- 📝 确定输入与输出
- 🔍 分析复杂度
- 🔨 复杂题目拆分 :严谨且完整 地拆分为更小的可以解决的子问题(字符的逻辑拆分)–(多总结)
- 💭 选择处理逻辑: 根据拆分后的子问题,总结并选择合适的问题处理思路(反转,替换etc)
- 🔎 检查特殊情况:边界条件和特殊情况
- 🏁 返回结果
344.反转字符串
class Solution {public void reverseString(char[] s) {int len = s.length;int left = 0, right = len - 1;char temp;while (left < right) {temp = s[left];s[left] = s[right];s[right] = temp;left++;right--;}}
}
541. 反转字符串II(逻辑+反转)
class Solution {public String reverseStr(String s, int k) {int len = s.length();int count = len/(2*k), others = len%(2*k);char[] c = s.toCharArray();for (int i = 0; i < count; i++) {reverse(c, 2*k*i, 2*k*i+k-1);}if (others < k && others > 0) reverse(c, 2*k*count, len-1);if (others < 2 * k && others >= k) reverse(c, 2*k*count, 2*k*count+k-1);return String.valueOf(c);}private void reverse(char[] c, int start, int end) {while(start < end) {char temp = c[start];c[start] = c[end];c[end] = temp;start++;end--;}}
}
卡码网:54.替换数字(替换)
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String s = sc.next();System.out.println(reverseWords(s,"number"));}public static String reverseWords(String s, String str) {StringBuilder stb = new StringBuilder();for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (c - '1' >= 0 && c - '1' <= 9) {stb.append(str);} else {stb.append(c);}}return stb.toString();}
}