题目:编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
示例 :
输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
1.原创
class Solution {
public:
void reverseString(vector<char>& s) {
int n = s.size();
for (int i=0,j=n-1;i<j;++i,--j){
swap(s[i],s[j]);//swap是库函数里的交换
}
}
};
2.题解
class Solution {
public:
void reverseString(vector<char>& s) {
if(s.size() <= 1)
return;
auto f = s.begin(); //迭代器
auto l = s.end()-1;
char tmp;
while(f < l)
{
tmp = *f;
*f = *l;
*l = tmp;
f += 1;
l -= 1;
}
return;
}
};
作者:wkltljjs
链接:https://leetcode-cn.com/problems/reverse-string/solution/die-dai-qi-by-wkltljjs-a4sr/