zoukankan      html  css  js  c++  java
  • 寻找第一个出现两次的字符

    解法1: O(n^2)的效率。也就是最简单的两重循环。

    解法2: 更好也更多被采用的,hash方法。定义一个256的数组就可以了。

    例如:“abcadfgrtybh”

    代码:

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <stdlib.h>
     4 int main()
     5 {
     6     char str[64] = "abcadfgrtybh";
     7     char ch;
     8     int i,j;
     9     for(i = 0;i < strlen(str);++i)
    10     {
    11         ch = str[i];
    12         for(j = i+1;j < strlen(str);++j)
    13         {
    14             if(ch == str[j])
    15             {
    16                 printf("%c",str[i]);
    17                 i = strlen(str);
    18                 break;
    19             }
    20         }
    21     }
    22 }
    View Code

    解法二的代码可以参见剑指Offer的“寻找第一个出现一次的字符”,得

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <stdlib.h>
     4 int main()
     5 {
     6     char str[64] = "qywyer23tdd";
     7     int hash[256];
     8     int i,j;
     9     for(i = 0;i < 256;++i)
    10     {
    11         hash[i] = 0;
    12     }
    13     for(j = 0;j < strlen(str);++j)
    14     {
    15         ++hash[str[j]];
    16     }
    17     for(i = 0;i < strlen(str);++i)
    18     {
    19         if(hash[str[i]] == 2)
    20         {
    21             printf("%c",str[i]);
    22             break;
    23         }
    24     }
    25 }
    View Code
  • 相关阅读:
    【leetcode】1230.Toss Strange Coins
    2018.12.25 SOW
    L203 词汇题
    L202
    L201
    L200
    2018
    2018.12.21 Cmos- RF
    L198
    L196 Hospital educations
  • 原文地址:https://www.cnblogs.com/sxmcACM/p/4800168.html
Copyright © 2011-2022 走看看