From : https://leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
class Solution {
public:
void reverseWords(string &s) {
stack<string> stc;
string tstr="";
s += ' ';
int len = s.length();
for(int i=0; i<len; i++) {
if(i==0 && s[i]==' ') continue;
if(s[i]==' ' && s[i-1]==' ') continue;
if(s[i]==' ' && tstr!="") {
stc.push(tstr);
tstr = "";
} else {
tstr += s[i];
}
}
s="";
while(!stc.empty()) {
s += stc.top();
stc.pop();
if(stc.empty()) {
break;
}
s += " ";
}
}
};Solution 2:
class Solution {
public:
void reverseWords(string &s) {
string ts;
int end = s.size()-1, start = end;
while(end>=0) {
while(end>=0 && s[end]==' ') end--;
start = end;
while(start>=0 && s[start]!=' ') start--;
if(start!=0 && start<end && ts!="") ts.append(" ");
if(start < end) ts.append(s.substr(start+1, end-start));
end = start;
}
s = ts;
}
};
本文介绍了一道LeetCode经典题目“翻转字符串中的单词”的两种解法。第一种解法利用栈来存储单词,然后依次弹出实现翻转;第二种解法采用双指针从字符串末尾开始寻找单词并进行翻转。这两种方法均能有效地解决该问题。
487

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



