151. Flip the word in the string

Answer:

  1. Go back and forths, all non-spaces are words, and the words are stacked in turn.
  2. The words are successively off the stack, separated by Spaces, connected into a new string, you can realize the flip.
/ * * *@param {string} s
 * @return {string}* /
var reverseWords = function (s) {
  let stack = []; // Use a stack to store words in a string
  let word = ' '; // Temporarily cache words
  let result = ' '; // Store the flipped string

  // Walk through the string to find all the words
  for (let i = 0; i < s.length; i++) {
    // If a space is encountered and the word is found, it is put on the stack
    if (s[i] === ' '&& word ! = =' ') {
      stack.push(word);
      word = ' '; // Empty the cache after the word is pushed
    } else if(s[i] ! = =' ') {
      // If a non-space character is encountered, the word is encountered and stored in wordword += s[i]; }}// If there are still words left after traversal, continue to push
  // Avoid ignoring the last word
  if (word) {
    stack.push(word);
  }

  // Store the last word first in the result
  result += stack.pop();

  // Roll the elements out of the stack
  while (stack.length) {
    // Separate words with Spaces
    result += ' ' + stack.pop();
  }

  // Return the result
  return result;
};
Copy the code
  1. Can besYou can create a stack by simply cutting it into an array with Spaces.
/ * * *@param {string} s
 * @return {string}* /
var reverseWords = function (s) {
  // Cut strings into arrays, naturally arranged in stack order
  let stack = s.trim().split(/\s+/);
  let word = ' '; // Temporarily cache words
  let result = ' '; // Store the flipped string

  // If there are still words left after traversal, continue to push
  // Avoid ignoring the last word
  if (word) {
    stack.push(word);
  }

  // Store the last word first in the result
  result += stack.pop();

  // Roll the elements out of the stack
  while (stack.length) {
    // Separate words with Spaces
    result += ' ' + stack.pop();
  }

  // Return the result
  return result;
};
Copy the code