Reverse String

Source: leetcode 344. Reverse String

Q. Write a function that takes a string as input and returns the string reversed.

Example:
Given s = “hello”, return “olleh”

Answer 1: Using two pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {string} s
* @return {string}
*/
export default function reverseString (s) {
const arr = s.split('')
const half = arr.length / 2 | 0
for (let i = 0; i < half; i++) {
const temp = arr[i]
arr[i] = arr[arr.length - i - 1]
arr[s.length - i - 1] = temp
}
return arr.join('')
}

Answer 2: Using simple string concatenation

1
2
3
4
5
6
7
8
9
10
11
/**
* @param {string} s
* @return {string}
*/
export default function reverseString (s) {
let reversed = ''
for (let i = s.length - 1; i >= 0; i--) {
reversed += s.charAt(i)
}
return reversed
}

Share Comments