算法训练营day08 字符串(反转,替换,综合运用(逻辑+反转))

时间:2024-07-14 21:46:45

???? 解题思路

  1. ???? 确定输入与输出
  2. ???? 分析复杂度
  3. ???? 复杂题目拆分严谨且完整 地拆分为更小的可以解决的子问题(字符的逻辑拆分)–(多总结
  4. ???? 选择处理逻辑: 根据拆分后的子问题,总结并选择合适的问题处理思路(反转,替换etc)
  5. ???? 检查特殊情况:边界条件和特殊情况
  6. ???? 返回结果

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();
    }
}