代码随想录二刷第七天 | 344.反转字符串、541. 反转字符串II、卡码网54.替换数字、卡码网55. 右旋字符串

51 阅读2分钟

344.反转字符串

题目:344. 反转字符串 - 力扣(LeetCode)

题解:代码随想录 (programmercarl.com)

状态:AC

思路

首尾指针快速AC

代码

时间复杂度:O(n) 空间复杂度:O(1)

class Solution {
    public void reverseString(char[] s) {
        int i = 0; int j = s.length - 1;
        while(i < j){
            char temp = s[j];
            s[j--] = s[i];
            s[i++] = temp;
        }
    }
}

# 541. 反转字符串II

题目:541. 反转字符串 II - 力扣(LeetCode)

题解:代码随想录 (programmercarl.com)

状态:AC

思路

在遍历字符串的过程中,只要让i += (2 * k),i每次移动 2*k 就可以了,然后判断是否需要有反转的区间

代码

时间复杂度:O(n) 空间复杂度:O(n)

class Solution {
    public String reverseStr(String s, int k) {
        char[] c = s.toCharArray();
        for(int i = 0; i < c.length; i += 2 * k){
            if(i + k <= c.length){
                reverse(c, i, i + k - 1);
            }else{
                reverse(c, i, c.length - 1);
            }
        }
        return new String(c);
    }

    public void reverse(char[] c, int l, int r){
        while(l < r){
            char temp = c[l];
            c[l++] = c[r];
            c[r--] = temp;
        }
    }
}

卡码网:54.替换数字

题目:54. 替换数字(第八期模拟笔试) (kamacoder.com)

题解:替换数字 | 代码随想录 (programmercarl.com)

状态:AC

代码

时间复杂度:O(n) 空间复杂度:O(1)

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String res = "";
        String s = sc.nextLine();
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) >= 'a' && s.charAt(i) <= 'z'){
                res += s.substring(i, i + 1);
            }else{
                res += "number";
            }
        }
        System.out.println(res);
    }
}

卡码网:55. 右旋字符串

题目:右旋字符串 | 代码随想录 (programmercarl.com)

题解:右旋字符串 | 代码随想录 (programmercarl.com)

状态:半AC

思路

先整体反转再局部反转

代码

时间复杂度:O(n) 空间复杂度:O(n)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        String s = in.nextLine();

        int len = s.length();  //获取字符串长度
        char[] chars = s.toCharArray();
        reverseString(chars, 0, len - 1);  //反转整个字符串
        reverseString(chars, 0, n - 1);  //反转前一段字符串,此时的字符串首尾尾是0,n - 1
        reverseString(chars, n, len - 1);  //反转后一段字符串,此时的字符串首尾尾是n,len - 1
        
        System.out.println(chars);

    }

    public static void reverseString(char[] ch, int start, int end) {
        //异或法反转字符串,参照题目 344.反转字符串的解释
        while (start < end) {
            ch[start] ^= ch[end];
            ch[end] ^= ch[start];
            ch[start] ^= ch[end];
            start++;
            end--;
        }
    }
}