344. Reverse String - LeetCode

344. Reverse String

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

Example 1:

Input: “hello”
Output: “olleh”

Example 2:

Input: “A man, a plan, a canal: Panama”
Output: “amanaP :lanac a ,nalp a ,nam A”

Solution:

// 创建新串
// Time:O(n), Space:O(n);
class Solution {
public:
string reverseString(string s) {
string str;
for (int i = s.length()-1; i >= 0; i--) {
str += s[i];
}
return str;
}
};
// 折半交换
// Time: O(n), Space: O(1)
class Solution {
public:
string reverseString(string s) {
int n = s.length();
for (int i = 0; i <= floor(n/2)-1; i++) {
char tmp = s[i]; s[i] = s[n-1-i];; s[n-1-i] = tmp;
}
return s;
}
};
// two pointers
// Time: O(n), Space: O(1)
class Solution {
public:
string reverseString(string s) {
int n = s.length();
int i = 0, j = n-1;
while (i < j) {
int tmp = s[i]; s[i] = s[j]; s[j] = tmp;
i++; j--;
}
return s;
}
};