LeetCode344—Reverse String
原题
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
分析
最简单的考虑就是从后往前挨个字符串拷贝到新串中再返回,这里利用rbegin()和rend()
加构造函数的方法更简单:
代码1
class Solution {
public:
string reverseString(string s) {
string ss(s.rbegin(),s.rend());
return ss;
}
};
有没有办法说不用额外的空间就在原串上修改?
其实把字符串分为左右两部分对应位置的字符进行交换即可。
代码2
class Solution {
private:
void chrSwap(char &a, char &b)//字符交换
{
char tmp = a;
a = b;
b = tmp;
}
public:
string reverseString(string s) {
int left = 0;
int right = s.size() - 1;
while (left < right)
{
chrSwap(s[left++], s[right--]);
}
return s;
}
};