题目描述:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

 

思路:先将句子全部反转,然后逐个翻转每个单词。

剑指offer : 反转单词顺序列

代码:

class Solution {
public:
	string ReverseSentence(string str) 
	{
		reverse(str.begin(), str.end());
		int word_begin = 0;
		int word_end = 0;
		while (word_end < str.size())
		{
			while (word_begin < str.size() && str[word_begin] == ' ')
			{
				word_begin++;
			}
			word_end = word_begin;
			while (word_end < str.size() && str[word_end] != ' ')
			{
				word_end++;
			}
			reverse(str.begin() + word_begin, str.begin() + word_end);
            word_begin = word_end;
		}
		return str;
	}
};

 

相关文章:

  • 2022-03-07
  • 2021-10-05
  • 2021-06-03
  • 2021-11-13
  • 2021-08-18
  • 2021-06-08
猜你喜欢
  • 2021-11-22
  • 2022-12-23
  • 2022-01-23
  • 2022-01-27
  • 2021-09-07
  • 2022-12-23
相关资源
相似解决方案