Reverse Words in a String
Total Accepted: 10990 Total Submissions: 79751Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
第一次在leetcode上做题,时间复杂度和空间复杂度就没怎么考虑。简单介绍下思路:
1 从前往后遍历,过滤空格,读取单词
2 把读到的单词放到栈中
3 将栈中元素拷贝到string,单词间添加空格
Tips:考察边界情况,特别是空字符串("")和空格字符串(” “)以及一个字符的情况(”a“)。另外,首尾的空格也要过滤。
源码:
void reverseWords(string &s) {
stack<string> sta;
int i,j,k;
int size;
size = s.size();
if(size == 0) //空字符串处理
return;
i=0;
j=size-1;
while(i <= j && s[i] == ' ')
i++;
while(j >= i && s[j] == ' ')
j--;
while(i<=j) //考虑单个字符的情况
{
k = i;
while(i <= j && s[i] != ' ')
i++;
sta.push(s.substr(k, i-k));
if(i >= j)
break;
while(i <= j && s[i] == ' ')
i++;
}
string tmp="";
while(!sta.empty()) //空格字符串不进入此循环
{
if(!tmp.empty())
tmp.push_back(' ');
tmp.append(sta.top());
sta.pop();
}
s = tmp;
}
写完之后网上查了一下,发现有很多写得比楼主牛逼多了,不得不感慨下自己的码渣水平。
算是多提供一种思路:http://www.tuicool.com/articles/uQ3E7b
end