determine if a string has all unique characters?

前端 未结 16 1463
长发绾君心
长发绾君心 2020-12-28 08:29

Can anybody tell me how to implement a program to check a string contains all unique chars ?

16条回答
  •  醉话见心
    2020-12-28 09:36

    my original answer was also doing the similar array technique and count the character occurrence.

    but i was doing it in C and I think it can be simple using some pointer manipulation and get rid of the array totally

    #include 
    #include 
    #include 
    
    void main (int argc, char *argv[])
    {
        char *string;
        if (argc<2)
        {
            printf ("please specify a string parameter.\n");
            exit (0);       
        }
    
        string = argv[1];
        int i;
    
        int is_unique = 1;
        char *to_check;
        while (*string)
        {
            to_check = string+1;
            while (*to_check)
            {
                //printf ("s = %c, c = %c\n", *string, *to_check);
                if (*to_check == *string)
                {
                    is_unique = 0;
                    break;
                }
                to_check++;
            }
            string++;
        }
    
        if (is_unique)
            printf ("string is unique\n");
        else
            printf ("string is NOT unique\n");
    }
    

提交回复
热议问题