Skip to content

Commit f7a347a

Browse files
Added solution for word reverse.
1 parent 5a34c85 commit f7a347a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ Happy to accept any contributions to this in any langugage.
5656
21. [Leet Code 1239 - Maximum length of the unique character string](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) | [Solution](./level_medium/LeetCode_1239_MaxLength.ts)
5757
22. [Leet Code 445 - Add Numbers II](https://leetcode.com/problems/add-two-numbers-ii/) | [Solution 1](./level_medium/LeetCode%20445_Add%202%20Numbers_1.ts) | [Solution 2](./level_medium/LeetCode%20445_Add%202%20Numbers_2.ts)
5858
23. [Leet Code 59 - Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [Solution](level_medium/SpiralMatrixII.ts)
59+
24. [Leet Code 151 - Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Solution](level_medium/LeetCode_151_Reverse_Words_In_a_String.ts)
5960

6061

6162

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Leet Code 151
3+
*
4+
* Solution uses an approach to add words in a stack as we do a single iteration. Adding words with the space
5+
* boundaries are done via slicing the string from the position to position. Altrnatively, this can also be done
6+
* using concatenation as well.
7+
*
8+
* Once the words are in the stack, they are pulled out to form a string in reverse order.
9+
*
10+
* Time: O(n) since each element is visited once, and O(n) space since additional storage of stack is used.
11+
*
12+
* @param s
13+
*/
14+
function reverseWords(s: string): string {
15+
const stack: string[] = []
16+
17+
// Add all the items to a stack.
18+
let start = 0, end = 0;
19+
for (let idx = 0; idx < s.length; idx++) {
20+
if (s[idx] === " ") {
21+
if (start !== end) stack.push(s.slice(start, end));
22+
start = idx + 1, end = idx + 1;
23+
} else {
24+
end++;
25+
}
26+
}
27+
28+
// Adding last word
29+
if (start !== end) stack.push(s.slice(start, end));
30+
31+
// Reverse the items as a string.
32+
let result = stack.pop(), substr: string | undefined = ""
33+
while( (substr = stack.pop()) !== undefined) {
34+
result += " " + substr
35+
}
36+
37+
return result || "";
38+
};

0 commit comments

Comments
 (0)