Wednesday, May 14, 2014

Leetcode (Python): 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.

class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        solution = []
        inWord = False
        for i in range(0, len(s)):
            if (s[i]==' ' or s[i]=='\t') and inWord:
                inWord = False
                solution.insert(0, s[start:i])
                solution.insert(0, ' ')
            elif not (s[i]==' ' or s[i]=='\t' or inWord):
                inWord = True
                start = i
        if inWord:
            solution.insert(0, s[start:len(s)])
            solution.insert(0, ' ')
        if len(solution)>0:
            solution.pop(0)
        return ''.join(solution)

No comments :

Post a Comment