如何查找字符串中第一个重复字符

发布于 2022-10-15 07:52:52 字数 68 浏览 17 评论 0

如:“hello world”中 的 l
“my name is Amen”中的 m

要求O(n)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

暖伴 2022-10-22 07:52:52

建立一个256的数组A,初始都为0,取每个字符c,若A[c]==0则A[c]=1,反之c就是要的结果

早茶月光 2022-10-22 07:52:52

楼上说的是传说中的bitmap

人疚 2022-10-22 07:52:52

2楼的方法不错, 不过要预处理, 预处理的时间可能比较长, 我觉得如果是查找一个字符的话, 直接去搜索也挺快的

北风几吹夏 2022-10-22 07:52:52

2楼的方法是最佳的了。

  1. /* rptchr.c */
  2. #include <stdio.h>
  3. #include <string.h>
  4. int repeat_char(const char *s)
  5. {
  6.         char map[256];
  7.         unsigned char c;
  8.         memset(map, 0, sizeof(map));
  9.         while ((c = *s++) != '\0') {
  10.                 if (map[c]) {
  11.                         return c;
  12.                 }
  13.                 ++map[c];
  14.         }
  15.         return -1;
  16. }
  17. int show_first_repeated_char(const char *s)
  18. {
  19.         int c;
  20.         c = repeat_char(s);
  21.         if (c == -1) {
  22.                 printf("string %s don't have any repeated characters\n", s);
  23.                 return -1;
  24.         }
  25.         printf("first repeated character of string \"%s\" is '%c'\n", s, c);
  26.         return 0;
  27. }
  28. int main(void)
  29. {
  30.         show_first_repeated_char("hello world");
  31.         show_first_repeated_char("my name is Amen");
  32.         return 0;
  33. }

复制代码

萌辣 2022-10-22 07:52:52

《编程珠玑》

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文