[LeetCode] Reverse Words in a String

2014-11-24 10:54:37 · 作者: · 浏览: 0

Given an input string, reverse the string word by word.

For example,

Given s = "the sky is blue",

return "blue is sky the".

问题描述:给定一个字符串,把这个字符串以单词为单位反转,如上例所示。

这道题很简单的想法就是:得到最后位置的迭代器iter,然后从头到尾遍历整个字符串,当获取一个单词时,就将这个单词插入到iter的后面,直到结束。

如上例,首先获取末尾的迭代器iter,它指向s.end(),然后遍历整个字符串,首先获取单词the,将the插入到iter的位置,也就是blue的后面,字符串就变成了"the sky is blue the",然后获取单词sky,将sky插入到iter的位置,字符串就变成了"the sky is blue sky the",直到结束。(这只是思路,中间还要考虑空格等字符)

不过,在实现时,不容易将字符串插入到iter的后面,结果就用的stack来实现的。

将字符串中的单词读入到stack中,然后读取出来,重构这个字符串,就可以了。中间还要处理空格等特殊字符。

class Solution {
public:
    void reverseWords(string &s) {
       if(s.size() == 0)
			return;

		stack
  
    sta;
		string str;
		string::iterator beg = s.begin();
		while(beg != s.end() && *beg == ' ')
			++beg;
		while(beg != s.end()) {
			if(*beg == ' ') {
				sta.push(str);
				str.clear();
				++beg;
				while(beg != s.end() && *beg == ' ')
					++beg;
			}
			else {
				str += *beg;
				++beg;
			}
		}
		if(str.size())
		    sta.push(str);
		s.clear();
		while(!sta.empty()) {
			str = sta.top();
			sta.pop();
			s.append(str.begin(), str.end());
			s += " ";
		}
		if(s.size())
		    s.erase(s.end() - 1);
    }
};