剑指offer---翻转单词顺序
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
class Solution { public: void fanzhuandanci(string &word, int start, int end) { int i = start; int j = end; while (i <= j) { swap(word[i], word[j]); ++i; --j; } } string ReverseSentence(string str) { str +=" "; fanzhuandanci(str,0,str.size()-1); str +=" "; int start = 0; int end = 0; while (start<str.size()) { while (str[start] == ' '&&start<str.size()) { ++start; } end = start; while (str[end] != ' '&&end<str.size()) { ++end; } --end; fanzhuandanci(str, start, end); ++end; start = end; } return str.substr(1,str.size()-2); } };