本文主要是介绍151. Reverse Words in a String 186.Reverse Words in a String II 翻转单词顺序列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
解答
我们使用wi来表示第i个单词,用wi’表示翻转后的单词。注意,当将一个单词翻转两次后,可以得到原始的单词,即(wi’)’=wi。
输入的字符串是w1w2…wn。如果我们翻转整个字符串,我们将得到wn’…w2’w1’。然后我们将单词逐个翻转,就可以得到wn…w2w1。
class Solution {
public:void reverseWords(string &s) {int length = s.length();reverse(s.begin(),s.end());int read = 0;int write = 0;while(read < length){//skip leading white space and more than one white spaces between wordsif(s[read] == ' ')++read;else{//record the start of a wordint wordStart = read;//count the length of a wordwhile(read < length && s[read] != ' ')++read;//reverse current word reverse(s.begin() + wordStart,s.begin() + read);//copy current word to the appropriate positioncopy(s.begin() + wordStart,s.begin() + read,s.begin() + write);//move write to the end of current wordwrite += read - wordStart;//add white space between wordsif(write < length)s[write] = ' ';//move write one step forward ++write;}}//s is not a empty string or string of white spacesif (write){s = s.substr(0,write-1);}elses = "";}
};
这篇关于151. Reverse Words in a String 186.Reverse Words in a String II 翻转单词顺序列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!