Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
这道题没什么难度,直接从两头往中间走,同时交换两边的字符即可,参见代码如下:
解法一:
class Solution { public: string reverseString(string s) { int left = 0, right = s.size() - 1; while (left < right) { char t = s[left]; s[left++] = s[right]; s[right--] = t; } return s; } };
我们也可以用swap函数来帮助我们翻转:
解法二:
class Solution { public: string reverseString(string s) { int left = 0, right = s.size() - 1; while (left < right) { swap(s[left++], s[right--]); } return s; } };
类似题目: