c-mcbride

ReverseHyphenString.JS

Jan 28th, 2024 (edited)
997
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Write a function reverseHyphenString(string) that takes in a hyphenated string and returns a the hyphenated string reversed.
  2. //Added here because "reverse a string" is a classic interview question
  3.  
  4. //Time complexity: O(n)
  5. //Space complexity: O(n)
  6. function reverseHyphenString(string){
  7.     let choppedString = string.split("-") //Split the array at the hyphen
  8.     let reversedString = []
  9.  
  10.     //Iterate backwards through the orignal word and add it to the reversed Array
  11.     for(let i = choppedString.length - 1; i >= 0; i--){
  12.         reversedString.push(choppedString[i])
  13.     }
  14.     reversedString = reversedString.join("-") //Join with a hyphen inserted. Thanks JS
  15.     return reversedString;
  16. }
  17.  
  18. console.log(reverseHyphenString("Go-to-the-store")) // => "store-the-to-Go"
Advertisement
Add Comment
Please, Sign In to add comment