题目描述
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:“Let’s take LeetCode contest”
输出:“s’teL ekat edoCteeL tsetnoc”
提示:
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路说明
刚开始的时候,将每个单词逐个进行翻转,思路很简单,效果也很差。
class Solution {
public:
string swap(int lo,int hi,string s){//反转单词
char temp;
while(lo<hi){
temp=s[lo];
s[lo++]=s[hi];
s[hi--]=temp;
}
return s;
}
string reverseWords(string s) {
int lo=0,hi=0;
while(hi<s.size()){
if(s[hi] !=' '){
hi++;
}
else{
s=swap(lo,hi-1,s);
hi++;
lo=hi;
}
}
s=swap(lo,hi-1,s);
return s;
}
};
运行结果如下,真的巨差。。。
要从算法的思路上进行改进,然后我又想起了我亲爱的栈,一番操作之后有所提升,但还是挺差的。
代码如下:
class Solution {
public:
string reverseWords(string s) {
stack<char>temp;
int lo=0,hi=0;
while(hi<s.size()){
if(s[hi] !=' '){
temp.push(s[hi]);
hi++;
}
else{
while(lo<hi){
s[lo++]=temp.top();
temp.pop();
}
hi++;
lo=hi;
}
}
while(lo<hi){
s[lo++]=temp.top();
temp.pop();
}
return s;
}
};
今天太晚了呜呜,还没想出比较好的方法。明天继续!