C笔试题|找最长字符串

嵌入式Linux

共 2941字,需浏览 6分钟

 ·

2022-11-01 18:25

如题,这个是一个在面试中很常见的题目

比如给出字符串

111 2222 333 44444 555555 66 77777

需要得出里面最长的字符串,要怎么写代码

正常思路

给一个变量开始计数,如果没有遇到空格就++i,遇到空格了就停止,结束后就判断之前计数的哪个变量是最大的。

代码

#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;
}

上面的代码有点容易,还是之前的那个朋友,写了一个风骚的版本,大家看看

#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;
}

上面用到了几个知识点

  • 递归,这个大家应该都能看出来了
  • 过滤空格 || 之前的代码都是过滤空格的
*_^0x20 //是过滤空格的代码
  • &&||的短路作用
exp1;
exp2;
等价于
=====
(exp1,0)||exp2;
或者
(exp1,1)&&exp2;
  • 返回最大值

大家有不清楚的地方可以在评论区提问,或者看出代码的妙处的,可以评论说出自己的观点。


浏览 31
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报