孙晓聪
  • 最新
  • 博客
  • 书评
  • Reverse Words in a String III

    Description

    doc

    Solutions

    First Idea

    /**
     * @param {string} s
     * @return {string}
     */
    var reverseWords = function (s) {
      return s
        .split(' ')
        .map((word) => word.split('').reverse().join(''))
        .join(' ')
    }
    

    -- Time Complexity: O(n) -- Space Complexity: O(n)

    Manual way

    /**
     * @param {string} s
     * @return {string}
     */
    var reverseWords = function (s) {
      let result = []
      let i = 0
      let cur = 0
    
      while (cur < s.length) {
        while (s.charAt(cur) !== ' ' && cur < s.length) {
          cur++
        }
    
        let end = s.charAt(cur) === ' ' ? cur - 1 : cur
        let rightCur = end
        while (i <= end) {
          result[i++] = s.charAt(rightCur--)
        }
    
        if (s.charAt(cur) === ' ') {
          result[i++] = s.charAt(cur)
        }
        cur++
      }
    
      return result.join('')
    }
    

    -- Time Complexity: O(n) -- Space Complexity: O(n)