-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreverse-words-in-a-string.js
92 lines (86 loc) · 2.05 KB
/
reverse-words-in-a-string.js
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
/**
* Source: https://leetcode.com/problems/reverse-words-in-a-string/
* Tags: [String]
* Level: Medium
* Title: Reverse Words in a String
* Auther: @imcoddy
* Content: Given an input string, reverse the string word by word.
*
*
*
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
*
*
*
* Update (2015-02-12):
* For C programmers: Try to solve it in-place in O(1) space.
*
*
* click to show clarification.
*
* Clarification:
*
*
*
* What constitutes a word?
* A sequence of non-space characters constitutes a word.
* Could the input string contain leading or trailing spaces?
* Yes. However, your reversed string should not contain leading or trailing spaces.
* How about multiple spaces between two words?
* Reduce them to a single space in the reversed string.
*/
/**
* @param {string} str
* @returns {string}
*/
/**
* Memo:
* Runtime: 123ms
* Tests: 22 test cases passed
* Rank: A
*/
var reverseWords = function(str) {
var start = 0;
var end = 0;
var result = [];
str = str.trim();
while (start < str.length) {
while (start < str.length && str.charAt(start) === ' ') {
start++;
}
end = start;
while (end < str.length && str.charAt(end) !== ' ') {
end++;
}
// console.log(start, end, str.slice(start, end), str);
result.push(str.slice(start, end));
start = end;
}
return result.reverse().join(' ');
};
/**
* Memo:
* Runtime: 259ms
* Tests: 22 test cases passed
* Rank: D
*/
var reverseWords = function(str) {
if (!str) {
return '';
}
var words = str.trim().split(' ');
var result = '';
words.forEach(function(e) {
if (e !== '') {
result = e + ' ' + result;
}
});
return result.trim();
};
console.log(reverseWords(''));
console.log(reverseWords('test'));
console.log(reverseWords('this is a test'));
console.log(reverseWords(' this is a test '));
console.log(reverseWords(' this is a test '));