14 ms Java Solution with explaination


  • 0
    E
     public String reverseWords(String s) {
            if(s==null || s.length()<=1){
                return s;
            }
            char[] c = s.toCharArray();
            
            int si = 0;
            int ei = 1;
            int len=c.length;
            
            while(ei<=len){
                if(c[ei-1]!=' ' && (ei==len || c[ei]==' ')){
                    //find the end of word, we need to do revser
                    reverse(c, si, ei-1);
                }else if(ei==len){
                    //to end of the file.and the prvious is not word
                    //skip
                }else if(c[ei-1]==' ' && c[ei]!=' '){
                    //find the first char of the word
                    si=ei;
                }
                ei++;
            }
            return new String(c);
        }
        
        private void reverse(char[] c, int si, int ei){
            while(si<ei){
                char temp = c[si];
                c[si]=c[ei];
                c[ei]=temp;
                si++;
                ei--;
            }
        }
    

Log in to reply
 

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