天天看點

leetcode 344.反轉字元串(reverse string)C語言

leetcode 344.反轉字元串(reverse string)C語言

    • 1.description
    • 2.solution

1.description

https://leetcode-cn.com/problems/reverse-string/description/

編寫一個函數,其作用是将輸入的字元串反轉過來。輸入字元串以字元數組 char[] 的形式給出。

不要給另外的數組配置設定額外的空間,你必須原地修改輸入數組、使用 O(1) 的額外空間解決這一問題。

你可以假設數組中的所有字元都是 ASCII 碼表中的可列印字元。

示例 1:

輸入:[“h”,“e”,“l”,“l”,“o”]

輸出:[“o”,“l”,“l”,“e”,“h”]

示例 2:

輸入:[“H”,“a”,“n”,“n”,“a”,“h”]

輸出:[“h”,“a”,“n”,“n”,“a”,“H”]

2.solution

void reverseString(char* s, int sSize){
    int l = 0, r = sSize-1;
    char tmp;
    while(l < r){
        char tmp = s[l];
        s[l] = s[r];
        s[r] = tmp;
        l++;
        r--;
    }

    return s;
}
           

繼續閱讀