剑指offer_58_翻转单词顺序I【javascript】

53 阅读1分钟

题目链接

leetcode.cn/problems/fa…

题目(简单)

输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串 "I am a student.",则输出 "student. a am I"。

题解

双指针+倒序遍历

复杂度分析

  • 时间复杂度 O(N) : 其中 N 为字符串 s 的长度,线性遍历字符串。
  • 空间复杂度 O(N) : 新建的 res 中的字符串总长度 ≤ N ,占用 O(N) 大小的额外空间。
/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    s = s.trim();                               // 删除首尾空格
    let j = s.length - 1, i = j;
    const res = [];
    while (i >= 0) {
        while (i >= 0 && s.charAt(i) != ' ') i--;     // 搜索首个空格
        res.push(s.substring(i + 1, j + 1) + " ");  // 添加单词
        while (i >= 0 && s.charAt(i) == ' ') i--;     // 跳过单词间空格
        j = i;                                              // j 指向下个单词的尾字符
    }
    return res.join('').trim(); 
};