LeetCode刷题实战344:反转字符串
Write a function that reverses a string. The input string is given as an array of characters s.
示例
示例 1:
输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:
输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
解题
class Solution {
public:
void reverseString(vector<char>& s) {
//不加这一句也能通过,加上可以避免一些问题。
if(s.size()==0) return ;
int left = 0, right = s.size() - 1;
while (left < right) {
swap(s[left++], s[right--]);
}
}
};
评论