Java LeetCode 151. Reverse words in a string

Given a string, flip each word in the string one by one.
Note:
No space characters form a word.
The input string can include extra spaces before or after it, but the reversed characters cannot be included.
If there is an extra space between two words, reduce the space between the words after inversion to only one.
Example 1:
Input: "the sky is blue"
Output: "blue is sky the"

Hesitating recursion is to push from back to front, you can use this property to reverse

class Solution {
    
    
    public String reverseWords(String s) {
    
    
        StringBuilder strs = new StringBuilder();
        rev(s,0,strs);
        return strs.toString().trim();
    }
    public void rev(String s,int left,StringBuilder sss){
    
    
        while(left<s.length()&&s.charAt(left)==' '){
    
    
            left++;
        }
        if(left==s.length()){
    
    
            return;
        }
        int right = left;
        while(right<s.length()&&s.charAt(right)!=' '){
    
    
            right++;
        }
        
        rev(s,right,sss);

        sss.append(s,left,right).append(' ');


    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/113092433