Processing math: 100%

Leetcode 344 - Reverse String

題目

Problem#

反轉一個字串

follow-up: in-place 且 O(1)

想法#

雙指標,反轉即可

  • 時間複雜度: O(n)
  • 空間複雜度: O(1)

AC Code#

Copy
class Solution
{
public:
void reverseString(vector<char>& s)
{
int i = 0, j = s.size()-1;
while(i <= j)
{
swap(s[i++], s[j--]);
}
}
};
view raw 344.cpp delivered with ❤ by emgithub