-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_113.js
More file actions
30 lines (25 loc) Β· 795 Bytes
/
problem_113.js
File metadata and controls
30 lines (25 loc) Β· 795 Bytes
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
// https://leetcode.com/problems/reverse-words-in-a-string/
//
// O(N) Time complexity
// O(N) Space complexity
// N is the number of words in the phrase
/**
* Given string of words, reverse words
* @param {string} phrase
* @return {string}
*/
function reverseString(phrase) {
const forward = phrase.split(' ');
const reverse = [];
// Base case
if (forward.length < 1) return phrase;
// Add to front of array
for (let i = 0; i < forward.length; i++) {
if (forward[i]) reverse.unshift(forward[i]);
}
return reverse.join(' ');
}
console.log(reverseString('hello world here')); // 'here world hello'
console.log(reverseString('hello world i am here')); // 'here am i world hello'
console.log(reverseString('hello')); // 'hello'
console.log(reverseString(' ')); // ' '