作者:陈太汉
单词翻转问题是个大公司常考的一个面试题,在网上看了不少实现方法,感觉都有瑕疵,在下今天又无聊一次,自己写了两种实现方式
一个是简洁版,一个是效率版
简洁版当然是简洁明了,思路清晰,很容易看懂,但是效率上有待改进,等改进之后发现发现就不是那么好理解了,所以就有了效率版,
个人还是主张简洁版,它看起来实在是舒服,让我很是满意。
为什么说简洁版效率有瑕疵呢?就是因为方法InvertWord的参数是值传递,就会不断的有变量构造和析构,
效率版就是解决这个问题,改为引用传递,但是引用传递又产生了另一些问题。看一下代码,你会懂的。
//将一句话翻转
// I am a student--> student a am I
//先整句话翻转,再每个单词翻转
精简版:
include<iostream> #include<string> using namespace std; class InvertWords{ public: InvertWords(string* wo):words(wo){} void Invert() { int len=words->size(); int beg=-1; //翻转整个字符串 InvertWord(beg,len); //翻转每个单词 for(int i=0;i<len;i++) { if(words->at(i)==' ') { InvertWord(beg,i); beg=i; } } } private: void InvertWord(int beg,int end) { char tmp; while(++beg<--end) { tmp=words->at(beg); words->at(beg)=words->at(end); words->at(end)=tmp; } } string* words; };
效率版:
#include<iostream> #include<string> using namespace std; class InvertWords2{ public: InvertWords2(string* wo):words(wo){} void Invert() { int len=words->size(); int beg=-1,k; //翻转整个字符串 InvertWord(beg,len); //由于方法InvertWord的参数为引用类型,beg和len的值都被修改了,所以要还原他们的值 beg=-1; len=words->size(); //翻转每个单词 for(int i=0;i<len;i++) { k=i;//k的作用就是保存现场,为了还原i到当前值 if(words->at(i)==' ') { InvertWord(beg,i); i=k;//还原i beg=i; } } } private: void InvertWord(int& beg,int& end) { char tmp; while(++beg<--end) { tmp=words->at(beg); words->at(beg)=words->at(end); words->at(end)=tmp; } } string* words; };