翻转字符串里的单词 - lifengyu360/lifengyu_first_git_test GitHub Wiki
给定一个字符串,逐个翻转字符串中的每个单词。
说明:
无空格字符构成一个 单词 。 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 示例 1: 输入:"the sky is blue" 输出:"blue is sky the"
class Solution {
public:
string reverseWords(string s) {
stack<string> all_str;
if (s.empty()
|| (std::string::npos == s.find(" ")) ) {
return s;
}
size_t start=0,index = s.find_first_of(" ", 0);
while(index != std::string::npos)
{
if(start!=index)
all_str.push(s.substr(start,index-start));
start = index+1;
index=s.find_first_of(" ",start);
}
if (!s.substr(start).empty()) {
all_str.push(s.substr(start));
}
string result;
while (!all_str.empty() ) {
result += all_str.top();
all_str.pop();
if (!all_str.empty()) result += " ";
}
return result;
}
};