LeetCode 344: Reverse String (字符串翻轉)

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

Note:1.注意空間複雜度,不需要重新分配內存,直接在原字符串上進行操作。 2.swap()函數的使用, swap函數原型如下:

template <class T> void swap ( T& a, T& b )  
{  
  T c(a); a=b; b=c;  
} 


Code:
class Solution {
public:
    string reverseString(string s) {
        int i=0, j = s.length()-1;
        while(i<j) swap(s[i++],s[j--]);
        return s;
    }
};


發佈了28 篇原創文章 · 獲贊 1 · 訪問量 5401
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章