Java iterative ac solution


  • 0
    R
    public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder();
            while(s.length() > 0) {                               
                int index = s.length();
                //traverse until meet space
                while(index > 0 && s.charAt(index-1) != ' ') {
                    index--;
                }
                String str = s.substring(index);
                // add if not space
                if(!str.isEmpty())  sb.append(str).append(" ");
                // traverse until not space
                while(index > 0 && s.charAt(index-1) == ' ') {
                    index--;
                }
                // truncate string and itaratively solve it
                s = s.substring(0, index);
            }
            // remove last empty space
            if(sb.length() > 0)     sb.setLength(sb.length()-1);
            return sb.toString();
        }
    

Log in to reply
 

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