Categories
interview

Reverse Words in a String – Java

Using a Stack
Uses O(n) memory and time.

public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        Stack<String> track = new Stack<String>();
        String word = "";
        int i=0;
        while (i < s.length()) {
            if (s.charAt(i) == ' ') {
                track.push(word);
                word = "";
                while(i<s.length() && s.charAt(i) == ' ')
                    i++;
                continue;
            }
            word +=s.charAt(i++);
        }
        if (word != "") {
            track.push(word);
        }
        s = "";
        while(!track.isEmpty()) {
            s+= track.pop()+" ";
        }
        
        return s.trim();
    }
}

Efficient Solution

Memory O(1) and O(n) time.

public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        StringBuffer ret = new StringBuffer(""); 
        int start, end = s.length()-1;
        int i=s.length()-1;
        while(i >= 0) {
            if(s.charAt(i) == ' ') {
                start = i+1;
                while(start<=end) {
                    ret.append(s.charAt(start++));
                }
                ret.append(" ");
                while(i>0 && s.charAt(i) == ' ') {
                    i--;
                }
                end = i;
                continue;
            }
            i--;   
        }
        start = 0;
        while(start<=end) {
            ret.append(s.charAt(start++));
        }
        return ret.toString();
    }
}

Using built-in java methods

public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
       String[] list = s.split(" ");
        s="";
        for(String curr: list) {
            if(curr.trim().length()>0)
             s = (s == "" ? curr.trim() : curr.trim() + " " + s);
        }
        return s;
    }
}