反转一个字符串中所有单词的位置
题目:给定一个字符串,逐个翻转字符串中的每个单词。
输入:" the sky is b|ue" 输出:" blue is sky the"
示例2
输入:" hello world! 输出:“Word!helo”
解释:输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例3
输入:" a good example" 输出:" example good a"
解释:如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
分析:去除空格用双指针的写法,反转每个单词以及反转整个字符串可以达到反转单词位置的效果
#include "_myPrint.cpp"
using namespace std;
class Solution{
public:
string removeExtraSpaces(string s){
int slowIndex = 0, fastIndex = 0;
// begin space
while (s.size() > 0 && fastIndex < s.size() && s[fastIndex] == ' '){
fastIndex++;
}
// middle space, just save one
for (; fastIndex < s.size(); fastIndex++){
if (fastIndex >= 1 && s[fastIndex] == s[fastIndex - 1] && s[fastIndex] == ' '){
continue;
}
s[slowIndex++] = s[fastIndex];
}
// end space, may have one or not
if (slowIndex >= 1 && s[slowIndex - 1] == ' '){
s.resize(slowIndex - 1);
}else{
s.resize(slowIndex);
}
return s;
}
string reverseEveryWord(string s){
int slowIndex = 0, fastIndex = 0;
for (; fastIndex < s.size(); fastIndex++){
if (s[fastIndex] == ' '){
reverse(s.begin() + slowIndex, s.begin() + fastIndex);
slowIndex = fastIndex + 1; // [ )
}
}
reverse(s.begin() + slowIndex, s.end());
return s;
}
string reverseWholeStr(string s){
reverse(s.begin(), s.end());
return s;
}
};
int main(){
Solution sl;
string s = " regdh fsfs ghdjl ";
s = sl.removeExtraSpaces(s);
s = sl.reverseEveryWord(s);
s = sl.reverseWholeStr(s);
cout << s << '$' << endl;
}