---
# System prepended metadata

title: Leetcode 344. Reverse String 練習
tags: [java, Leetcode, Algorithm]

---

# Leetcode 344. Reverse String 練習
> Difficulty : `Easy`
> `Java` `演算法Algorithm`

> 撰寫人[name=KVJK_2125] [time=SAT, May 18, 2024 17:40]

## 題目
### 說明 Description
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.

翻譯：
寫一個函數，其作用是將輸入的字串反轉過來。輸入字串以字元陣列s的形式給出。<br>
不要給另外的陣列分配額外的空間，你必須原地修改輸入陣列、使用O(1)的額外空間解決這個問題。

### 範例 Example
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
- `1 <= s.length <= 10^5`
- `s[i]` is a printable ascii character.

## 解題
### 思路 Intuition/Approach
- Step1.<br> ![image](https://hackmd.io/_uploads/Hkq7Zg9mR.png =80%x)


- Step2.<br> for 迴圈前，設定一個存放`s.length`的變數：<br>`int lengths = s.length`<br>

- Step3.<br> for迴圈中，設定一個變數`char boxtemp = s[i]`，存放左邊要被交換的值;<br>將左邊要被交換的＂位置＂放入右邊要交換的值`s[i] = s[--lengths]`;<br>將右邊要被交換的＂位置＂放入存放在`boxtemp`中的值

### 程式碼 Code（加註解）
```clink=
class Solution {
    public void reverseString(char[] s) {
        int lengths = s.length; //建立長度變數
        //交換
        for(int i = 0; i <= (s.length-1) / 2; i++)
        {
            char boxtemp = s[i];    //暫時存放左邊要被交換的值
            s[i] = s[--lengths];    //左邊要被交換的'位置'存放右邊要交換的值
            s[lengths] = boxtemp;   //右邊要被交換的'位置'存放左邊原本的值
        }
    }
}
```