151. Reverse Words in a String
Tags:
Medium
Skills:
String
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu đảo ngược thứ tự các từ trong một chuỗi, đảm bảo:
Approach - Built in function
Time and space complexity
Solution
1function reverseWords(s: string): string {
2 const trim = s.trim();
3 const words = trim.split(/\s+/);
4 words.reverse()
5 return words.join(' ');
6};Approach - Not use built in function
Solution
1function reverseWords(s: string): string {
2 const n = s.length;
3 let res = '';
4 let i = n -1;
5 while(i >= 0) {
6 while(i >= 0 && s[i] === ' ') i--;
7 if (i < 0) break;
8 let end = i;
9
10 while (i >= 0 && s[i] !== ' ') i--;
11 let start = i + 1;
12 if(res.length > 0) res += ' ';
13 for(let j = start; j <= end; j++) {
14 res += s[j]
15 }
16 }
17
18 return res;
19};while(i >= 0 && s[i]===' ')