筆試題目
//寫一個函數,將字符串翻轉,翻轉方式如下:“I am a student”反轉成“student a am I”,不借助任何庫函數。
據說這題在筆試或者面試當中,出現的頻率非常高。剛好在書上也看到這題,又在博客園看到這題出現了(“發職位經典面試題”)。
作者也提示了,方法是先反轉整個字符串,然后再反轉字串。譬如先將“I am a student”反轉為“tneduts a ma I”,然后再對每個字串(空格分割)反轉一次。思想就那么簡單吧。實現起來的話,我就有點凌亂了。C++沒學好。傷不起。
算法
1 #include <stdio.h> 2 3 void main() 4 { 5 char str[]="I am a student";
7 printf(str); 8 printf("\n"); 9 10 char *p,*q; 11 char temp; 12 p=q=str;14 while(*q!='\0') 15 { 16 q++; 17 } 18 q--; 19 while(p<=q) 20 { 21 temp=*p; 22 *p=*q; 23 *q=temp; 24 p++; 25 q--; 26 }//反轉整個字符串 27 28 printf(str); 29 printf("\n"); 30 31 q=str;//指針指向開始位置 32 char *s,*t; 33 s=t=str; 34 while(*q!='\0') 35 { 36 if(*q==' ') 37 { 38 t--; 39 while(s<=t) 40 { 41 temp=*t; 42 *t=*s; 43 *s=temp; 44 s++; 45 t--; 46 }//反轉局部字符串 47 48 s=q+1; 49 t=q; 50 }52 q++; 53 t++; 54 } 55 56 printf(str); 57 printf("\n"); 58 }
改進
運行之后,我發現是成功的。
但是怎么想都感覺有點問題,把“I am a student”換成“you are a student”果然有問題。
沒有處理最后一個字串的緣故。因為我是按照
if(*q==' ')
來處理字串的,而字符串最后一個的結尾沒有空格了,而是以'\0'結尾的。
最后一個字串的處理我是這樣做的。
if(*q==' '||*(q+1)=='\0') { t--; if(*(q+1)=='\0')//處理最后一個字串 t++;
看上去有點奇怪吧,但是確實是可以了。
代碼貌似可以繼續優化吧。怎么都感覺自己寫的代碼好爛。
代碼
以下是完整代碼

#include <stdio.h> void main() { char str[]="you are a student"; printf(str); printf("\n"); char *p,*q; char temp; p=q=str; while(*q!='\0') { q++; } q--; while(p<=q) { temp=*p; *p=*q; *q=temp; p++; q--; }//反轉整個字符串 printf(str); printf("\n"); char *s; q=p=s=str;//指針指向開始位置 while(*q!='\0') { if(*q==' '||*(q+1)=='\0') { p--; if(*(q+1)=='\0')//處理最后一個字串 p++; while(s<=p) { temp=*p; *p=*s; *s=temp; s++; p--; }//反轉局部字符串 s=q+1; p=q; } q++; p++; } printf(str); printf("\n"); }
另外給一個我在《程序員面試寶典》看到的代碼,不過這個主要采用數組處理,而且使用了庫函數(strlen()),但是思想差不多吧。可以參考參考。

#include <iostram> #include <stdio.h> int main(void) { int num=-12345,j=0,i=0,flag=0,begin,end; char str[]="I am a student",temp; j=strlen(str)-1; printf(" string=%s\n",str); //第一步是進行全盤反轉,將單詞變成“tneduts a ma I” while(j>i) { temp=str[i]; str[i]=str[j]; str[j]=temp; j--; i++; } printf(" string=%s\n",str); int i=0; //第二步進行部分反轉,如果不是空格則開始反轉單詞 while(str[i]) { if(str[i]!=' ') { begin=i; while(str[i]&&str[i]!=' ') { i++; } i=i-1; end=i; } while(end>begin) { temp=str[begin]; str[begin]=str[end]; str[end]=temp; end--; begin++; } i++; } printf(" string=%s\n",str); return 0; }
既然看到了,就應該要思考吧。僅提升..
參考 《程序員面試寶典(第二版)》 開發職位經典面試題 http://www.cnblogs.com/zhangjing230/archive/2012/05/17/2505711.html