Algorithms and Data Structures – Reversed Strings
--- Directions
Given a string, return a new string with the reversed
order of characters
--- Examples
reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'
First Solution
1. Turn 'str' into an array
2. Call 'reverse' method on the array
3. Join the array back into a string
4. Return the result
1 2 3 4 5 6 | function reverse(str) { return str .split('') .reverse() .join(''); } | cs |
Second Solution
- Created an empty string called 'reversed'
- for each character in the provided string
take the character and add it to the start of 'reversed' - Return the variable 'reversed'
1 2 3 4 5 6 7 8 9 | function reverse(str) { let reversed = ''; for (let character of str) { reversed = character + reversed } return reversed; } | cs |
Third Solution
1 2 3 4 5 | function reverse(str) { return str.split('').reduce((reversed, character) => { return character + reversed; }, ''); } | cs |