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"
分析:题目要找到string的逆序,两种思路,第一种交换--双指针问题,第二种思路,考虑用std库实现
class Solution {
public:
string reverseString(string s) {
// 使用 std::begin(), std::end() 实现
std::reverse(std::begin(s), std::end(s));
return s;
}
};
class Solution {
public:
string reverseString(string s) {
// 使用 string 自带的 begin(), end() 实现
std::reverse(s.begin(), s.end());
return s;
}
};
class Solution {
public:
string reverseString(string s) {
// 使用双指针进行交换,reverse 的实现
int i = 0, j = s.size() - 1;
while (i < j) {
std::swap(s[i], s[j]);
i++;
j--;
}
return s;
}
};