反转字符串中的单词 III (Reverse Words in a String III)

 

思路:直接原地反转

// @Title: 反转字符串中的单词 III (Reverse Words in a String III)
// @Author: qisiii
// @Date: 2022-03-10 20:03:13
// @Runtime: 3 ms
// @Memory: 41.6 MB
// @comment: 直接原地反转
// @flag: RED
class Solution {
    public String reverseWords(String s) {
        char[] ch=s.toCharArray();
        int left=0,index=0;
        while(index<s.length()){
            if(ch[index++]==' '){
                reverse(ch,left,index-2);
                left=index;
            }
        }
        reverse(ch,left,s.length()-1);
        return new String(ch);
    }
    public void reverse(char[] charArray,int left,int right){
        while(left<right){
            char temp=charArray[left];
            charArray[left]=charArray[right];
            charArray[right]=temp;
            left++;right--;
        }
    }
}

+++ title = “反转字符串中的单词 III (Reverse Words in a String III)” draft = false +++

思路:通过stringbuilder进行拼接,拼接倒序的单词

// @Title: 反转字符串中的单词 III (Reverse Words in a String III)
// @Author: qisiii
// @Date: 2022-03-10 19:58:54
// @Runtime: 21 ms
// @Memory: 42.2 MB
// @comment: 通过stringbuilder进行拼接,拼接倒序的单词
// @flag: BLUE
class Solution {
    public String reverseWords(String s) {
        StringBuilder str=new StringBuilder();
        char[] ch=s.toCharArray();
        int left=0,index=0;
        while(index<s.length()){
            if(ch[index++]==' '){
                str.append(reverse(ch,left,index-2));
                str.append(' ');
                left=index;
            }
            if(index==s.length()){
                str.append(reverse(ch,left,index-1));
            }
        }
        return str.toString();
    }
    public String reverse(char[] charArray,int left,int right){
        StringBuilder str=new StringBuilder();
        for(int i=right;i>=left;i--){
            str.append(charArray[i]);
        }
        System.out.println(str);
        return str.toString();
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18