Created
January 1, 2020 14:09
-
-
Save ironars/d70496ae6f7d2fa2f81dd4e34edf2704 to your computer and use it in GitHub Desktop.
How to reverse words in a character array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Input: [ | |
| // "J", | |
| // "o", | |
| // "i", | |
| // "n", | |
| // " ", | |
| // "U", | |
| // "s", | |
| // " ", | |
| // "N", | |
| // "o", | |
| // "w" | |
| // ] | |
| var data = "Join Us Now".split(""); // creates the input array. | |
| function reverseLettersOnly(arr) { | |
| if (!arr.length) return arr; | |
| let start = 0; | |
| let end = arr.length; | |
| let spaceIndex = -1; | |
| for (let index = 0; index < arr.length; index++) { | |
| if (arr[index] === " ") { | |
| spaceIndex = index; | |
| end = spaceIndex; | |
| } | |
| if (spaceIndex >= 0) { | |
| console.log("spaceIndex: ", spaceIndex); | |
| // end = index - 1; | |
| console.log("old arr:", arr); | |
| const subArr = arr.slice(start, end).reverse(); | |
| console.log("subArr: ", subArr); | |
| arr.splice(start, end - start, ...subArr); | |
| console.log("new arr: ", arr); | |
| start = spaceIndex + 1; | |
| end = arr.length - 1; | |
| spaceIndex = -1; | |
| console.log("start: ", start); | |
| console.log("end: ", end); | |
| } else if (index === arr.length - 1) { | |
| // single word | |
| console.log("start: ", start); | |
| console.log("end: ", end); | |
| const subArr = arr.slice(start).reverse(); | |
| arr.splice(start, end, ...subArr); | |
| } | |
| } | |
| } | |
| reverseLettersOnly(data); | |
| console.log("result: ", data); |
Author
spaceIndexis required to set the next value forstart.
see this!
https://github.com/nomanalikhan/hacker-rank-solutions/blob/master/reverse-letters-only/solution.js
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
spaceIndexis required to set the next value forstart.