字符串按word反转
方法一、不用栈
void reverseChar(char* str, int len) { char* q = str+len-1; char* p = str; if (!len) return; while( p<q ) { char tmp = *p; *p = *q; *q = tmp; p++; q--; } for (int i=0; i<len; i++) cout << str[i]; cout << endl; } void reverseWord(char* str) { char* p = str; int count = 0; int total = 0; while(1) { p++; count++; total++; if ( *p==' ' || *p=='\0' ) { reverseChar(p-count, count); //note that, it is -1,not 0 count=-1; if ( *p=='\0' ) { break; } } } reverseChar(str, total); }
方法二、采用了两个stack,一个用于整个字符串的反转,一个用于保证word内部顺序不变。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
char * reverse_word( char * str) { stack< char > st; stack< char > word; char * p = str; st.push( '\0' ); while ( *p != '\0' ) { while ( *p == ' ' ) st.push(*p++); if ( *p == '\0' ) break ; while ( *p != '\0' && *p != ' ' ) word.push(*p++); while ( !word.empty() ) { st.push( word.top() ); word.pop(); } } p = str; while ( *p != '\0' ) { *p = st.top(); st.pop(); p++; } return str; }
|