Simple and clean solution


  • 0
    G
    public class Solution {
        public String reverseWords(String s) {
            
            StringBuilder sbr = new StringBuilder();
            int start = 0;
            while(start<s.length()){
                // Append all white spaces first
                while(start < s.length() && s.charAt(start) == ' '){
                    sbr.append(' ');
                    start++;
                }
                if(start < s.length()){
                    int end = start;
                    // Figure out when next space occurs. This will give boundary of current word
                    while(end < s.length() && s.charAt(end) != ' '){
                        end++;
                    }
                    // Reverse and append word
                    sbr.append(reverseString(s, start, end-1));
                    start = end;
                }
                
            }
        
            return sbr.toString();
        }
        
       // Reverses string between start and end index 
        private String reverseString(String s, int start, int end){
            StringBuilder sbr = new StringBuilder();
            for(int i=end;i>=start;i--){
                sbr.append(s.charAt(i));
            }
    
            
            return sbr.toString();
        }
    }
    

Log in to reply
 

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