-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-words-in-a-string.js
More file actions
109 lines (89 loc) · 2.4 KB
/
reverse-words-in-a-string.js
File metadata and controls
109 lines (89 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Problem: Reverse Words in a String
* Link: https://leetcode.com/problems/reverse-words-in-a-string/
* Difficulty: Medium
*
* Given an input string s, reverse the order of the words.
* A word is defined as a sequence of non-space characters.
*
* Example:
* Input: s = "the sky is blue"
* Output: "blue is sky the"
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
// JavaScript Solution - Built-in methods
function reverseWords(s) {
return s.trim().split(/\s+/).reverse().join(" ");
}
// Alternative: Manual approach without built-in reverse
function reverseWordsManual(s) {
const words = [];
let word = "";
// Extract words
for (let i = 0; i < s.length; i++) {
if (s[i] !== " ") {
word += s[i];
} else if (word.length > 0) {
words.push(word);
word = "";
}
}
// Don't forget last word
if (word.length > 0) {
words.push(word);
}
// Reverse and join
let result = "";
for (let i = words.length - 1; i >= 0; i--) {
result += words[i];
if (i > 0) result += " ";
}
return result;
}
// Test cases
console.log(reverseWords("the sky is blue")); // "blue is sky the"
console.log(reverseWords(" hello world ")); // "world hello"
console.log(reverseWords("a good example")); // "example good a"
module.exports = reverseWords;
/* Python Solution (commented):
def reverse_words(s: str) -> str:
"""
Reverse words in a string
Args:
s: Input string
Returns:
String with reversed word order
Time Complexity: O(n)
Space Complexity: O(n)
"""
return ' '.join(reversed(s.split()))
# Alternative: Manual approach
def reverse_words_manual(s: str) -> str:
words = []
word = ''
# Extract words
for char in s:
if char != ' ':
word += char
elif word:
words.append(word)
word = ''
# Don't forget last word
if word:
words.append(word)
# Reverse and join
return ' '.join(reversed(words))
# Alternative: Two-pass approach
def reverse_words_two_pass(s: str) -> str:
# Split and filter empty strings
words = [word for word in s.split() if word]
# Reverse
words.reverse()
return ' '.join(words)
# Test cases
print(reverse_words("the sky is blue")) # "blue is sky the"
print(reverse_words(" hello world ")) # "world hello"
print(reverse_words("a good example")) # "example good a"
*/