Code Maintenance & Programming Rules

 This guide outlines essential best practices spanning code style, architectural design, debugging, testing, performance, and portability—all aimed at reducing the long-term cognitive load of code maintenance. 🎨 1. Style Code is written for humans to read, and only incidentally for computers to execute. Variable Naming : Use descriptive names for global variables, and short names for local variables. Precision and Consistency : Use active names for functions (e.g., calculateTotal ). Above all, keep your coding style consistent throughout the project. Structure & Expressions : Use a consistent indentation and brace ( {} ) style to show program structure visually. Use the natural form for expressions. Use parentheses to make the semantics unambiguous. Break up overly complex expressions to keep them clear. Side Effects & Macros : Beware of functions with side effects. Avoid function-like macros; if unavoidable, parenthesize the macro body and arguments carefully. Magic Numbe...

LeetCode 解題練習:Reverse String

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

If you like this post, please click the ads on the blog or buy me a coffee. Thank you very much.

題目原文描述 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--;
        }
    }
};

留言

這個網誌中的熱門文章