Tuesday, February 24, 2015

Reverse Words in a String

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
Solution: O(n) runtime, O(n) space
One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.
We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.
public class Solution {
    public String reverseWords(String s) {
        StringBuilder result = new StringBuilder();
        int len = s.length();
        
        for(int i = s.length() - 1; i >= 0; i--) {
            if(s.charAt(i) == ' ') {
                len = i;
            }else if(i == 0 || s.charAt(i - 1) == ' ') {
                if(result.length() != 0) {
                    result.append(' ');
                }
                result.append(s.substring(i, len));
            }
        }
        return result.toString();
    }
}

No comments:

Post a Comment