0

I have solved this problem, but still feel I could improve in some areas.

I know this problem can be solved using slicing and reversed build- in functions.But I am doing this as a practice for interview coding questions.So wanted this way

How did I approach in solving the problem:

  1. Covert the input string to a list . I did this since in python strings are immutable.
  2. Reverse the entire list of characters
  3. Reverse the individual words.
  4. #Problem area:Once the list is ready with the words reversed , joining back to a string dealing with spaces seems to be problematic to me. ex: INPUT:' helpful is overflow stack ' -- > Output 'stack overflow is helpful'

    ## My Code ##

class Solution: # @param word, a list of chars # @param startInd, an int # @param endInd, an int # @return a list of reversed characters def reverseChars(self,word,starIndex,endIndex): lengthWord = endIndex-starIndex+1 # Reverse the characters of the word by swapping the corresponding chars # Looping for only lengthWord/2 times should suffice for i in xrange(0,lengthWord/2): word[starIndex + i],word[endIndex-i]=word[endIndex-i],word[starIndex +i] return word

# @param s, a string
# @return a string
def reverseWords(self, s):
    #Convert given input string into list of characters.
    listChars = list(s)

    #First reverse the entire string.
    self.reverseChars(listChars,0,len(listChars)-1)

    # Iterate through the list of reversed chars and reverse individual word.
    # Iterate through the list till we find a space and then call the reverseChars function.
    startind = 0 
    endind = -1
    space = ' '
    for x in listChars:
        if(x == space):
            if(listChars[startind]== startind<len(listChars)-1):
                startind+=1
                endind+=1
            else:
                self.reverseChars(listChars,startind,endind)
                endind = endind+1
                startind = endind + 1
        else:
            endind+=1
    self.reverseChars(listChars,startind,endind)
--> return ' '.join(''.join(listChars).split())

Can my last return statement with join statements be improved?

mittu
  • 1
  • 1

0 Answers0