2020年6月4日 星期四

Leetcode題解 Python & C#:六月挑戰DAY4 Reverse String

寫一個功能反轉 char 陣列,在內部修改,不用回傳值。

對於初學物件導向的人,很容易用新的實例來取代原本的,不過如果是 C# 等,就得宣告才會產生新的,自然不會有混淆的問題。(比較少)

反轉字串的方式,就是最前與最後開始兩兩交換,換到 len()//2 之前停止。

Python
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        ls = len(s)
        for i in range(ls//2):
            s[i], s[ls-1-i] = s[ls-1-i], s[i] 
C#
public class Solution {
    public void ReverseString(char[] s) {
        int l = s.Length-1;
        for(int i = 0; i < (l+1)/2; i++)
        {
            char lc = s[i];
            s[i] = s[l-i];
            s[l-i] = lc;
        }
    }
}