# 344. Reverse String

## 題目敘述

Write a function that reverses a string. The input string is given as an array of characters s`.

You must do this by modifying the input array in-place with `O(1)` extra memory.

Example 1:

``````Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
``````

Example 2:

``````Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
``````

Constraints:

Hint 1:

The entire logic for reversing a string is based on using the opposite directional two-pointer approach!

## 解法解析

### 解法範例

#### Go

``````func reverseString(s []byte) {
left := 0
right := len(s) - 1
for left < right {
s[left], s[right] = s[right], s[left]
left++
right--
}
}
``````

#### JavaScript

``````/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function (s) {
let left = 0,
right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
};
``````

#### Kotlin

``````class Solution {
fun reverseString(s: CharArray): Unit {
val n = s.size

for (i in 0..(n / 2 - 1)) {
val temp = s[i]
s[i] = s[n - 1 - i]
s[n - 1 - i] = temp
}
}
}
``````

#### PHP

``````class Solution
{

/**
* @param String[] \$s
* @return NULL
*/
function reverseString(&\$s)
{
\$left = 0;
\$right = count(\$s) - 1;
while (\$left < \$right) {
\$temp = \$s[\$left];
\$s[\$left] = \$s[\$right];
\$s[\$right] = \$temp;
\$left++;
\$right--;
}
}
}
``````

#### Python

``````class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left, right = left + 1, right - 1
``````

#### Rust

``````impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {
let mut left = 0;
let mut right = s.len() - 1;
while left < right {
s.swap(left, right);
left += 1;
right -= 1;
}
}
}
``````

#### Swift

``````class Solution {
func reverseString(_ s: inout [Character]) {
let middel = Int(s.count / 2)
for i in 0..<middel {
let temp = s[i]
s[i] = s[s.count - 1 - i]
s[s.count - 1 - i] = temp
}
}
}
``````

### Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!