Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Javascript Reverse Words O(n) time O(1) space

function reverseWords(message) {

  // First we reverse all the characters in the entire message
  reverseCharacters(message, 0, message.length - 1);
  // This gives us the right word order
  // but with each word backward

  // Now we'll make the words forward again
  // by reversing each word's characters

  // We hold the index of the *start* of the current word
  // as we look for the *end* of the current word
  let currentWordStartIndex = 0;
  for (let i = 0; i <= message.length; i++) {

    // Found the end of the current word!
    if (i === message.length || message[i] === ' ') {

      // If we haven't exhausted the string our
      // next word's start is one character ahead
      reverseCharacters(message, currentWordStartIndex, i - 1);
      currentWordStartIndex = i + 1;
    }
  }
}

function reverseCharacters(message, leftIndex, rightIndex) {

  // Walk towards the middle, from both sides
  while (leftIndex < rightIndex) {

    // Swap the left char and right char
    const temp = message[leftIndex];
    message[leftIndex] = message[rightIndex];
    message[rightIndex] = temp;
    leftIndex++;
    rightIndex--;
  }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: dangerously meaning 
Javascript :: react pass object to state 
Javascript :: splice javascript list 
Javascript :: Scotch.io - Create a CRUD App with Node and MongoDB 1 Getting Started 
Javascript :: one dimensional array in javascript 
Javascript :: Return Early Pattern for Functions 
Javascript :: self excuting arrow function 
Javascript :: SHOPIFY STORE FRONT PASSWORD 
Javascript :: What can I put in the parentheses of an if statement to make it false 
Javascript :: vanilla javascript event when reach bottom of element no jquery 
Javascript :: how scroll bottom simplebar in vue js 
Javascript :: To enable server-to-server and REST tools like Postman to access our API - 
Javascript :: public url react for serving django static in production 
Javascript :: setFocus() in searchbar ionic4 
Javascript :: complite nodejs remove ubuntu 
Javascript :: fetch Mongodb find() results with Backbone 
Javascript :: Get JSON Key In Array Alternative Syntax 
Javascript :: Angular active router change event 
Javascript :: _.extend() underscore 
Javascript :: Both This Have The Same Value 
Javascript :: how to create element with class in javascript 
Javascript :: use stigviewr 
Javascript :: react email validation 
Javascript :: hoe to find items in mongoose 
Javascript :: $() in javascript 
Javascript :: react Dark/Light mode 
Javascript :: NodeJS Multi-Core Processors Example 
Javascript :: devexpress image collection 
Javascript :: find leap year javascript 
Javascript :: js if on cellular network 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =