描述:
微软面试题:将一个句子按单词反序
将一个句子按单词反序。比如 “hi baidu com mianshiti”,反序后变为 “mianshiti com baidu hi”。
分析:
一般的想法,把所有的字符反转,然后把单个的单词再次反转。。。
提供两种代码:纯c和stl版
View Code
1 #include <iostream> 2 using namespace std; 3 4 char * Reverse(char *p) 5 { 6 int len =strlen(p); 7 if(len == 0) 8 { 9 cout << "字符串为空"<<endl; 10 return 0; 11 } 12 int m =0,n=len-1; 13 char temp =0; 14 while(m <= n) 15 { 16 /*交换操作可以用异或运算替代*/ 17 temp = p[m]; 18 p[m] = p[n]; 19 p[n] = temp; 20 m++; n--; 21 } 22 int st =0; 23 for(int i=0;i<len;i++) 24 { 25 if(p[i] == ' ') 26 { 27 int j = st,k = i-1; 28 while(j <= k) 29 { 30 temp = p[j]; 31 p[j] = p[k]; 32 p[k] = temp; 33 j++; k--; 34 } 35 st = i+1; 36 } 37 } 38 m = st; n = len -1; 39 while(m <= n) 40 { 41 temp = p[m]; 42 p[m] = p[n]; 43 p[n] = temp; 44 m++; n--; 45 } 46 return p; 47 } 48 void main() 49 { 50 char a[] = "hi baidu com mianshiti"; 51 cout << Reverse(a) << endl; 52 }
View Code
// STL #include <iostream> #include <vector> #include <algorithm> using namespace std; char * Reverse(char *p) { if(p != NULL) {cout << "string is free..."<<endl; return 0;} char *q; q = p; vector<char> vec; vector<char>::iterator vec_it; while(*p != '\0') { vec.push_back(*p); p++; } reverse(vec.begin(),vec.end()); // 注意reverse函数中参数二应该在区间终端迭代指针的后一位 vector<char>::iterator st = vec.begin(); for(vec_it = vec.begin();vec_it != vec.end();vec_it++) { if(*vec_it == ' ') { reverse(st,vec_it); st = vec_it+1; } } reverse(st,vec_it); char *qq = q; for(vec_it = vec.begin();vec_it != vec.end();vec_it++) { *qq = *vec_it; qq++; } *qq = '\0'; return q; } void main() { char a[] = "hi baidu com mianshiti"; cout << Reverse(a) << endl; }
现在还是觉得,纯c在自己的掌控中,stl用得还是不能得心应手...... 希望看完<<c++标准程序库>>能够懂得stl的工作原理。。。