LeetCode-字符串

Posted by 黑矮皮卡 on October 25, 2024

反转字符串

class Solution {
    public void reverseString(char[] s) {
        int l=0,r=s.length-1;
        while(l<r){
            char tem=s[l];
            s[l]=s[r];
            s[r]=tem;
            l++;
            r--;
        }
    }
}

反转字符串II

class Solution {
    public String reverseStr(String s, int k) {
        char[]arr=s.toCharArray();
        int n=s.length();
        for(int i=0;i<n;i+=2*k){
            reverse(arr,i,Math.min(n,i+k)-1);
        }
        return new String(arr);
    }
    public void reverse(char[]arr,int l,int r){
        while(l<r){
        char tem=arr[l];
        arr[l]=arr[r];
        arr[r]=tem;
        l++;
        r--;
    }
    }
}

反转字符串中的单词

//双指针倒序遍历字符串
class Solution {
    public String reverseWords(String s) {
        s=s.trim();
        int i=s.length()-1,j=i;
        StringBuilder res=new StringBuilder();
        while(i>=0){
            while(i>=0&&s.charAt(i)!=' '){
                i--;
                }
                res.append(s.substring(i+1,j+1)+" ");
            while(i>=0&&s.charAt(i)==' '){
                i--;
            }
                j=i;
            }
                    return res.toString().trim();
        }
    }