557.反转字符串中的单词III----LeetCode(java实现)

解题思路:

分为三步:

(1)先将字符串整个反转

(2)将反转后得到的字符串以空格为分隔符进行分割

(3)将分割后得到的字符数组倒序遍历,并在数组下标非0的地方加上空格,便得到结果字符串

class Solution {
    public String reverseWords(String s) {
    StringBuilder builder=new StringBuilder();
        int len=s.length();
        for(int i=len-1;i>=0;--i){
            builder.append(s.charAt(i));
        }
        String res="";
        String[] temp=builder.toString().split(" ");
        int size=temp.length;
        for(int j=size-1;j>=0;--j){
            res+=temp[j];
            if(j>0){
                res+=" ";
            }
        }
        return res;
    }
}

 

你可能感兴趣的:(LeetCode)