当前位置: 移动技术网 > 科技>操作系统>windows > 如何将it is good 转换成 good it is

如何将it is good 转换成 good it is

2020年09月01日  | 移动技术网科技  | 我要评论
今天看到了个面试题,如标题所言,it is good转换成good it is,看似很简单,我自信满满的开始写了,然后写出来了谁看到都想打我的代码。string Reverse(string & s){ string tmp1; string tmp2; string tmp3; int count1 = 0; int count2 = 0; auto it = s.begin(); while(*it !=' ') { count2++; }

今天看到了个面试题,如标题所言,it is good转换成good it is,看似很简单,我自信满满的开始写了,然后写出来了谁看到都想打我的代码。

string Reverse(string & s)
{
  string tmp1;
  string tmp2;
  string tmp3;
  int count1 = 0;
  int count2 = 0;
  auto it = s.begin();
  while(*it !=' ')
  {
      count2++;
  }
  tmp1 = s.substr(count1,count2-1); 
  count1 = count2;
  it++;
  while(*it != ' ')
  {
    count2++;
    it++;
  }
  tmp2 = s.substr(count1,count2);
  count1 = count2;
  while(it != s.end())
  {
    count2++;
    it++;
  }
  tmp3 = s.substr(count1,count2);

  tmp3 += tmp1;
  tmp3 += tmp2;
}

先刨除bug不说,就这个写法,估计谁看了都会把我骂一顿,感觉就像个刚开始学Helllo World的人写的一样,我还真是这个想法。因为我分析了哈这个题,很多要素我感觉我处理不好,比如说这个\0怎么处理,这个空格到底包含给谁,怎么组装顺序,然后我就想出来用三个string分块把代码装进去,就写出了这个很垃圾的版本,还没处理好空格。
最后瞅了瞅解题步骤
先上源码,


void reverse_word(char*p,char*q){
  char temp;
  while(q>p){
    temp=*p;
    *p=*q;
    *q=temp;
    q--;
    p++;

  }

}

char* indexofnoletter(char*p){
  char*t=p;
  while(*t!=' '&&*t!='\0')
    t++;
  return --t;

}

int main(){
  char a[]="this is good";
  puts(a);
  reverse_word(a,a+strlen(a)-1);
  char*p,*q;
  p=a;
  do{
    q=indexofnoletter(p);
    reverse_word(p,q);
    p=q+2;

  }while(p<=a+strlen(a)-1);

  puts(a);
return 0;
}

好吧,我傻逼了把题看错了,这个是把this is good 转换成 good it is
这个处理机制好多了,只需要将第一个单词和最后一个单词互换就行,因为单词长度都是一样长的,所以不存在\0空格安放问题。

总结就是,要看清楚题

本文地址:https://blog.csdn.net/flf1234567898/article/details/108585458

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网