LeetCode 解題練習:Reverse String
題目原文描述 https://leetcode.com/problems/reverse-string/
中文描述
給定一個字元陣列 s ,撰寫一個函式來反轉此字串。
注意請修改此陣列來完成程式碼。
範例一:
輸入 s = [ "a", "b", "c", "d", "e"]
輸出 ["e", "d", "c", "b", "a"]
範例二:
輸入 s = [ "G", "o", "o", "d", "s"]
輸出 ["s", "d", "o", "o", "G"]
解法:
使用兩個指標 left 與 right 分別表示陣列的頭與尾,從最左邊與最右邊依序互換。
Python Code
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left = 0
right = len(s) - 1
while left <= right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
C++ Code
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0, right = s.size() - 1;
while(left < right)
{
swap(s[left], s[right]);
left++;
right--;
}
}
};
若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
If you like this post, please click the ads on the blog or buy me a coffee. Thank you very much.

留言