My relatively simple Java solution beats 55% 10ms


  • 0
    E
    public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder();
            int k=s.length()-1;
            int begin=-1;
            int end = -1;
            boolean flag = false;
            while(k>=0){
                char c = s.charAt(k);
                if(c==' '&begin!=-1){
                    while(end>=begin){
                        sb.append(s.charAt(begin));
                        begin++;
                    }
                    begin=-1;
                    end=-1;
                    flag = true;
                }else if(c!=' '&&begin==-1){
                    if(flag)
                    sb.append(" ");
                    begin = k;
                    end = k;
                }else if(c!=' '&&begin!=-1){
                    begin--;
                }
                
                k--;
            }
            
            if(begin!=-1){
                while(end>=begin){
                        sb.append(s.charAt(begin));
                        begin++;
                } 
            }
            return sb.toString();
        }
    

Log in to reply
 

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