0%

reverse-string

Reverse String – LeetCode 344

Problem

Description

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

Example

Given s = “hello”, return “olleh”.

Answer

Original

Code

1
2
3
4
5
6
class Solution {
public:
string reverseString(string s) {
return string(s.rbegin(),s.rend());
}
};

思路

简单的逆向,时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$11$ ms,排名$81.34\%$

Better

思路

等价版本
耗时$11$ ms,排名$81.34\%$

Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
string reverseString(string s) {
int i = 0, j = s.size() - 1;
while(i < j){
swap(s[i++], s[j--]);
}

return s;
}
};