首页 > 代码库 > 翻转字符串

翻转字符串

代码:

class Solution {
public:
/**
* @param s : A string
* @return : A string
*/
string reverseWords(string s) {
int storeIndex = 0, n = s.size();
reverse(s.begin(), s.end());
for (int i = 0; i < n; ++i) {
if (s[i] != ‘ ‘) {
if (storeIndex != 0) s[storeIndex++] = ‘ ‘;
int j = i;
while (j < n && s[j] != ‘ ‘) s[storeIndex++] = s[j++];
reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
i = j;
}
}
return string(s.begin(), s.begin() + storeIndex);
}
};

截图:

技术分享

翻转字符串