C++双指针解字符串反转
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例1:
输入: “Let’s take LeetCode contest”
输出: “s’teL ekat edoCteeL tsetnoc”
class Solution {
public:
string reverseWords(string s) {
int len = s.size();
int left = 0,right = 0;
if(!len) return s;
while(right < len){
while(right < len && s[right] != ' ') right++;//找到空格位置
int next = right-- + 1;//保存当前空格位置
while(left < right) swap(s[left++],s[right--]);
right = next,left = next;
}
return s;
}
2万+

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



