给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
提示:
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
代码
class Solution { public: string reverseWords(string s) { if(s.size() == 0){ return s; } string res = s; int left = 0; while(left < s.size() && s[left] == ' '){ left++; } int right = left; while(right < s.size()){ while(right < s.size() && s[right] != ' '){ right++; } cout<<right<<endl; int tem_left = left; int tem_right = right - 1; while(tem_left<tem_right){ res[tem_left] = s[tem_right]; res[tem_right] = s[tem_left]; tem_left++; tem_right--; } right++; left = right; } return res; } };