[Array] LeetCode 151. Reverse Words in a String
First Solution O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def reverseWords(self, s: str) -> str:
        result = ""
        n = len(s)
        start, end = n, 0
        count = 0
        for i in range(n-1, -1, -1):
            if s[i] != " " and count == 0:
                end = i
                count = 1
            if s[i] != " " and count == 1:
                start = i
            if s[i] == " " and start <= end and count != 0:
                result += s[start:end+1] + " "
                count = 0
        if s[start:end+1] != " " and count != 0:
                result += s[start:end+1]
        return result if result[-1] != " " else result[:len(result) - 1]
- Iterate the string from the end.
 - Update the end index to the end index for each word.
 - Update the start index until it meets an empty space in the string s.
 - Add the word to the result if it meets an empty space and if the end index is updated (count != 0).
 - Check once more after iterating for the whole string, if there is a word to add to the result.
 
Second Solution O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    def reverseWords(self, s: str) -> str:
        res = []
        temp = ""
        for c in s:
            if c != " ":
                temp += c
            elif temp != "":
                res.append(temp)
                temp = ""
        if temp != "":
            res.append(temp)
        return " ".join(res[::-1])
- Add each character in s to the temp if it is not a blank space.
 - Add the created temp word to result, only if the temp word is not empty.
 - After iterating through the whole string, check once more if the temp is not empty and add it to the result if it is not empty.
 - Join the words in the result in reverse order.
 
 This post is licensed under  CC BY 4.0  by the author.