Write a function that reverses the input string. The input string is given as a character array s.
Instead of allocating extra space to another array, you must modify the input array in place, using O(1) extra space to solve the problem.
This is a relatively simple character string inversion problem, can directly use JS API, cyclic exchange, double pointer method to solve
- JS API
var reverseString = function(s) {
return s.reverse()
};
Copy the code
- Circulation exchange
Swap the i-th and (array length -i) elements by iterating through the array. The traversal length is math.floor (array length / 2).
var reverseString = function(s) {
for (let index = 0 ; index < Math.floor(s.length / 2); index++) {
let left = index
let right = s.length - 1 - index
let temp = s[left]
s[left] = s[right]
s[right] = temp
}
}
Copy the code
- Double pointer
Set the left and right Pointers of the array to be swapped. After the exchange, the left pointer moves, the right pointer moves left, until the two Pointers intersect, then the exchange ends
var reverseString = function(s) { let left = 0 let right = s.length - 1 while (left < right) { if (s[left] ! == s[right]) { let temp = s[left] s[left] = s[right] s[right] = temp } left++ right-- } }Copy the code
All three methods can reverse arrays.