solution with trim, easy to understand(java)


  • 0
    M
    public class Solution {
        public String reverseWords(String s) {
            s=s.trim();
            if(s.length()==0)return s;
            String[] strArray=s.split(" ");
            StringBuilder ret=new StringBuilder();
            for(int i=strArray.length-1;i>=0;i--){
                if(strArray[i].length()>0){
                    ret.append(" ").append(strArray[i]);
                }
            }
            ret.deleteCharAt(0);
            return ret.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.