determine if a string has all unique characters?

前端 未结 16 1294
长发绾君心
长发绾君心 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:33

    Use a HashTable, add the key for each character along with the count of occurrences as the value. Loop through the HashTable keys to see if you encountered a count > 1. If so, output false.

    0 讨论(0)
  • 2020-12-28 09:33

    Without using additional memory:

    #define UNIQUE_ARRAY 1
    int isUniqueArray(char* string){
        if(NULL == string ) return ! UNIQUE_ARRAY;
        char* current = string;
        while(*current){
            char* next   = current+1;
            while(*next){
                if(*next == *current){
                    return ! UNIQUE_ARRAY;
                }
                next++;
            }
            current++;
        }
        return UNIQUE_ARRAY;
    }
    
    0 讨论(0)
  • 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 <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    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");
    }
    
    0 讨论(0)
  • 2020-12-28 09:36

    this is optimal solution for the problem. it takes only an integer variable and can tell whether it is unique or not regardless of string size.

    complexity

    best case O(1)

    worst case O(n)

    public static boolean isUniqueChars(String str) {
        int checker = 0;
        for (int i = 0; i < str.length(); ++i) {
            int val = str.charAt(i) - ‘a’;
            if ((checker & (1 << val)) > 0) 
                return false;
            checker |= (1 << val);
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题