557. Reverse Words in a String I

2021-12-03  本文已影响0人  jluemmmm

反转句子形式的字符串

/**
 * @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('');
};
上一篇下一篇

猜你喜欢

热点阅读