PHP前端开发

Typescript 编码编年史:反转字符串中的单词

百变鹏仔 3天前 #JavaScript
文章标签 编年史

问题陈述:

给定一个输入字符串 s,反转单词的顺序。单词被定义为非空格字符的序列。 s 中的单词将至少由一个空格分隔。返回由单个空格按相反顺序连接的单词字符串。

注意 s 可能包含前导或尾随空格或两个单词之间的多个空格。返回的字符串应该只有一个空格来分隔单词。请勿包含任何多余空格。

示例1:

示例2:

示例3:

限制条件:

初步思考过程:

要解决这个问题,我们需要:

  1. 将字符串拆分成单词。
  2. 颠倒单词的顺序。
  3. 将单词重新连接在一起,每个单词之间有一个空格。

基本解决方案:

代码:

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 <h3>      时间复杂度分析:</h3>

基本解决方案的改进:

边缘情况和测试:

边缘情况:

  1. 字符串包含前导空格和尾随空格。
  2. 字符串中单词之间包含多个空格。
  3. 该字符串仅包含一个单词。
  4. 字符串长度达到最小或最大限制。

测试用例:

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("   ")); // ""

一般解决问题的策略:

  1. 理解问题:仔细阅读问题陈述,了解要求和约束。
  2. 识别关键操作: 确定所需的关键操作,例如拆分、反转、连接单词。
  3. 优化可读性: 使用清晰简洁的逻辑,确保代码易于理解。
  4. 彻底测试: 使用各种情况(包括边缘情况)测试解决方案,以确保正确性。

识别类似问题:

  1. 字符串操作:

  2. 双指针技术:

  3. 就地算法:

结论:

通过练习此类问题和策略,您可以提高解决问题的能力,并为各种编码挑战做好更好的准备。