LeetCode--Reverse Words in a String III

Ideas:

    Split the array into multiple words, flip each word, and join them together

class Solution {
    public String reverseWords(String s) {
        String[] words=s.split(" ");
        String[] res=new String[words.length];
        for(int i=0;i<words.length;i++){
            res[i]=reverse(words[i]);
        }
        
        String end="";
        for(int i=0;i<res.length;i++){
            end+=res[i];
            end+=" ";
        }
        
        return end.substring(0,end.length()-1);
    }
    
    private String reverse(String word){
        int length=word.length();
        char[] res=new char[length];
        for(int i=length-1;i>=0;i--){
            int pos=length-1-i;
            res[pos]=word.charAt(i);
        }
        
        return String.valueOf(res);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325647483&siteId=291194637