美文网首页
557. Reverse Words in a String I

557. Reverse Words in a String I

作者: jluemmmm | 来源:发表于2021-12-03 12:01 被阅读0次

    反转句子形式的字符串

    • Runtime: 84 ms, faster than 81.42%
    • Memory Usage: 45.7 MB, less than 20.66%
    • 时间复杂度O(n),空间复杂度O(n)
    /**
     * @param {string} s
     * @return {string}
     */
    var reverseWords = function(s) {
      let i = 0;
      let len = s.length;
      s = s.split('');
      while (i < len) {
        let start = i;
        while (i < len && s[i] !== ' ') {
          i++;
        }
        
        let left = start;
        let right = i - 1;
        
        while (left < right) {
          let tmp = s[left];
          s[left] = s[right];
          s[right] = tmp;
          left++;
          right--;
        }
         while (i < len && s[i] === ' ') {
          i++
        }
      }
      return s.join('');
    };
    

    相关文章

      网友评论

          本文标题:557. Reverse Words in a String I

          本文链接:https://www.haomeiwen.com/subject/gfipxrtx.html