Sunday, March 9, 2014

Leetcode: 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:

We implement it as a state-machine with two states


where in the transition we add the word or mark the beginning.

public class Solution {
    public String reverseWords(String s) {
        StringBuilder solution = new StringBuilder();
        int startOfWord = 0;
        boolean inWord = false;
        for(int i=0; i<s.length(); i++)
        {
            if(s.charAt(i)==' ' || s.charAt(i)=='\t')
            {
                if (inWord)
                {
                    solution.insert(0,s.substring(startOfWord,i));
                    solution.insert(0,' ');
                    inWord = false;
                }
            }
            else
            {
                if (!inWord)
                {
                    inWord=true;
                    startOfWord = i;
                }
            }
        }
        if (inWord)
        {
            solution.insert(0,s.substring(startOfWord,s.length()));
            solution.insert(0,' ');
        }
        if (solution.length()>0)
            solution.deleteCharAt(0);
        return solution.toString();
    }
}

No comments :

Post a Comment