Here's my python code for Reverse Words in a String question:
class Solution: def reverseWords(self,s): x = -1 y = len(s) output = '' while x != -len(s)-1: if s[x] != ' ' : x -= 1 elif s[x] == ' ': output = output + s[x:y] + ' ' y = x x -= 1 if x == -len(s)-1: output += s[0:y] return output
I've tested my code on my Mac and it works fine, however when I try to submit this piece of code to leetcode, there seems to be a runtime error:Runtime Error Message: Line 7: IndexError: string index out of range
Last executed input: " 1 "
I believe I can use list[-1] as the first element searching backward so I have no idea whats wrong with my code.
Thanks for helping.
Please do not do
return what problem required.
However, there is still room for improvement, after changing
print output to
return output in your code.
Thanks, I found this piece of code in discussion Q/As but this is not what I'm looking for. I just start learning Python couple days ago. Also, I believe there are other solutions to this question that is more easy to understand.
Thanks for your comment, I changed the print to return.
I get a Line 7: IndexError: string index out of range error and I'm still trying to google it out.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.