m*c 发帖数: 74 | 1 【 以下文字转载自 JobHunting 讨论区 】
【 原文由 mac 所发表 】
The program should monitor a possibly infinite stream of characters
from the keyboard (standard input). If it detects the sequence "aaa" it
outputs a "0". If it detects the sequence "aba" it outputs a "1".
DO NOT detect sequences within sequences. The program should exit
cleanly when it detects an End Of Input. For example:
The following sequence aababaaabaaa would produce the
following result: 100
While the following sequence aaaba | X****r 发帖数: 3557 | 2 if( p[0] == 'a' ) {
if( p[1] == 'a' ) {
if( p[2] == 'a' ) {
printf( "0" );
p += 3 ;
}else if( p[2] == 'b' ) {
if( p[3] == 'a' ) {
printf( "1" );
}
p += 4 ;
}else {
p += 3 ;
}
}else if ( p[1] == 'b' ) {
if( p[2] == 'a' ) {
printf( "1" );
}
p += 3 ;
}else {
p += 2 ;
}
}else {
p ++ ;
}
我也真够无聊的,写这种code
其实你原来的code除了= 以外就很好了,比我这个在simplicity上好得多,呵呵。
【在 m*c 的大作中提到】 : 【 以下文字转载自 JobHunting 讨论区 】 : 【 原文由 mac 所发表 】 : The program should monitor a possibly infinite stream of characters : from the keyboard (standard input). If it detects the sequence "aaa" it : outputs a "0". If it detects the sequence "aba" it outputs a "1". : DO NOT detect sequences within sequences. The program should exit : cleanly when it detects an End Of Input. For example: : The following sequence aababaaabaaa would produce the : following result: 100 : While the following sequence aaaba
| X****r 发帖数: 3557 | 3 其实就按本来面目写也很清楚,不用写成一堆条件,还不用缓冲区。
int ch, branch, state = 0 ;
int table[][2] = { { 1, 0 }, { 2, 3 }, { '0', 3 }, { '1', 0 } };
while( (ch = getchar()) != EOF )
( ch == 'a' && (branch = 0, 1) || ch == 'b' && (branch = 1, 1) ||(state=0))&&
( (state = table[state][branch]) == '0' || state == '1' ) &&
( putchar( state ), state = 0 ) ;
加注:面试的时候可不要写这种code,没拿到offer 不要怪我……,
了解我的意思就行了:)
【在 X****r 的大作中提到】 : if( p[0] == 'a' ) { : if( p[1] == 'a' ) { : if( p[2] == 'a' ) { : printf( "0" ); : p += 3 ; : }else if( p[2] == 'b' ) { : if( p[3] == 'a' ) { : printf( "1" ); : } : p += 4 ;
|
|