C筆試題|找最長(zhǎng)字符串
如題,這個(gè)是一個(gè)在面試中很常見(jiàn)的題目
比如給出字符串
111 2222 333 44444 555555 66 77777
需要得出里面最長(zhǎng)的字符串,要怎么寫(xiě)代碼
正常思路
給一個(gè)變量開(kāi)始計(jì)數(shù),如果沒(méi)有遇到空格就++i,遇到空格了就停止,結(jié)束后就判斷之前計(jì)數(shù)的哪個(gè)變量是最大的。
代碼
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
typedef struct {
char* p;
char len;
} world_t;
int main() {
char str[] = "May there be enough clouds in your life to make a beautiful sunset";
int pos = 0;
world_t world_s[100]= {0};
world_s[0].len = 0;
world_s[0].p = str;
for (int i = 0; i < sizeof(str); i++) {
if (str[i] != ' ') {
world_s[pos].len++;
} else {
pos++;
world_s[pos].p = &str[i+1];
str[i] = '\0';
}
}
world_t world_t_tmp;
world_t_tmp = world_s[0];
for (int i=0; i<=pos; i++) {
if (world_s[i].len > world_t_tmp.len) {
world_t_tmp = world_s[i];
}
}
printf("%d %s\n", world_t_tmp.len, world_t_tmp.p);
return 0;
}
上面的代碼有點(diǎn)容易,還是之前的那個(gè)朋友,寫(xiě)了一個(gè)風(fēng)騷的版本,大家看看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int maxword(char* _, int __, char** ___, int ____)
{
(((*_&0xf0)>>4>1 && *_^0x20 && ++__ || !(*_^0x20)&&(__=0)),0)||((*___=(__>(____=*_^0?maxword(++_, __, ___, 0):____))?_-__:*___));
return ____>__?____:__;
}
int main(int argc, char ** argv)
{
if (argc < 2) {
printf("usage: %s \"a string in bash\"\n",argv[0]);
return 0;
}
char * pos = argv[1];
int len = maxword(argv[1],0,&pos,0);
char *buf = malloc(len+1);
strncpy(buf, pos, len);
printf("maxlen of word in argv[1] %d %s\n",len, buf);
free(buf);
return 0;
}
上面用到了幾個(gè)知識(shí)點(diǎn)
遞歸,這個(gè)大家應(yīng)該都能看出來(lái)了 過(guò)濾空格 ||之前的代碼都是過(guò)濾空格的
*_^0x20 //是過(guò)濾空格的代碼
&&和||的短路作用
exp1;
exp2;
等價(jià)于
=====
(exp1,0)||exp2;
或者
(exp1,1)&&exp2;
返回最大值
大家有不清楚的地方可以在評(píng)論區(qū)提問(wèn),或者看出代碼的妙處的,可以評(píng)論說(shuō)出自己的觀點(diǎn)。

評(píng)論
圖片
表情
