Java solution using basic string operations only


  • 0
    F

    The idea is pretty straightforward: start from the end of the string, get rid of spaces, locate the word and append it to the the StringBuilder, then continue the process until we reach the beginning of the string. Just remember removing the extra space appended to the StringBuilder. Here is the program:

     public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder(s.length()); // for holding the reversed string
        int i = s.length() - 1; // beginning index of a word (inclusive)
        int j = i + 1;          // ending index of a word (exclusive)
        
        do {
            while (i >= 0 && s.charAt(i) == ' ') {
                i--;            // get rid of spaces
            }
            
            j = i + 1;          // ending index of the word
        
            while (i >= 0 && s.charAt(i) != ' ') {
                i--;            // locate the beginning index of the word
            }
            
            if (i + 1 < j) {
                sb.append(s.substring(i + 1, j) + " "); // append the word
            }
            
        } while (i >= 0);
        
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1); // get rid of the extra space we appended
        }
        
        return sb.toString();
    }

Log in to reply
 

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