344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
344. 翻转字符串
写一个翻转字符串的算法。
思路
使用两个index,一个从左到右,一个从右到左,将字符串中的字符交换。
代码
class Solution {
public:
string reverseString(string s) {
int i=0, j=s.size()-1;
while(i<j){
swap(s[i++], s[j--]);
}
return s;
}
};
本文介绍了一个简单的字符串翻转算法,通过双指针技术实现字符串的原地反转。该方法使用两个索引,一个从字符串开始位置向后遍历,另一个从末尾向前遍历,并在遍历过程中交换这两个位置上的字符。
737

被折叠的 条评论
为什么被折叠?



