
给定一个输入字符串 s,反转单词的顺序。单词被定义为非空格字符的序列。 s 中的单词将至少由一个空格分隔。返回由单个空格按相反顺序连接的单词字符串。
注意 s 可能包含前导或尾随空格或两个单词之间的多个空格。返回的字符串应该只有一个空格来分隔单词。请勿包含任何多余空格。
要解决这个问题,我们需要:
function reversewordsbruteforce(s: string): string {
// split the string by spaces and filter out empty strings
let words = s.trim().split(/\s+/);
// reverse the array of words
words.reverse();
// join the words with a single space
return words.join(' ');
}
考虑到限制,这个解决方案是有效的。但是,它为单词数组使用了额外的空间。
如果字符串数据类型是可变的,并且我们需要使用 o(1) 额外空间就地解决它,我们可以使用两指针技术来反转原始字符串中的单词。
function reversewordsoptimized(s: string): string {
// trim the string and convert it to an array of characters
let chars = s.trim().split('');
// helper function to reverse a portion of the array in place
function reverse(arr: string[], left: number, right: number) {
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
// reverse the entire array of characters
reverse(chars, 0, chars.length - 1);
// reverse each word in the reversed array
let start = 0;
for (let end = 0; end <= chars.length; end++) {
if (end === chars.length || chars[end] === ' ') {
reverse(chars, start, end - 1);
start = end + 1;
}
}
// join the characters back into a string and split by spaces to remove extra spaces
return chars.join('').split(/\s+/).join(' ');
}
console.log(reverseWordsBruteForce("the sky is blue")); // "blue is sky the"
console.log(reverseWordsBruteForce(" hello world ")); // "world hello"
console.log(reverseWordsBruteForce("a good example")); // "example good a"
console.log(reverseWordsBruteForce("singleWord")); // "singleWord"
console.log(reverseWordsBruteForce(" ")); // ""
console.log(reverseWordsOptimized("the sky is blue")); // "blue is sky the"
console.log(reverseWordsOptimized(" hello world ")); // "world hello"
console.log(reverseWordsOptimized("a good example")); // "example good a"
console.log(reverseWordsOptimized("singleWord")); // "singleWord"
console.log(reverseWordsOptimized(" ")); // ""
字符串操作:
双指针技术:
就地算法:
通过练习此类问题和策略,您可以提高解决问题的能力,并为各种编码挑战做好更好的准备。
以上就是Typescript 编码编年史:反转字符串中的单词的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号