CC189 - 1.1

Highlight:

1.ASCII string or unicode string (http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html)

2.if the string len > 256, cannot form a unique string

解法一:char set array

bool isUniqueChars(string str){
    int len = str.size();
    if(len>256){
        return false;
    }
    bool existBefore[256] = {};
    for(int i=0;i<len;i++){
        int pos = str[i];
        if(existBefore[pos]){
            return false;
        }else{
            existBefore[pos] = true;
        }
    }
    return true;
}

time complexity O(n) - n is the length of the string array; O(1) - for loop will never iterate through more than 256 characters

space complexity O(1) - the length of the character set array

 解法二:an integer array of 8

bool isUniqueChars(string str){
    int char_set[8] = {};
    for(int i=0;i<str.size();i++){
        int val = str[i];
        int pos = val/32, shift=val%32;
        if(char_set[pos]&(1<<shift)){
            return false;
        }
        char_set[pos] |= (1<<shift);
    }
    return true;
}

解法三:an integer (26 alphabets)

bool isUniqueChars(string str){
    int checker = 0;
    for(int i=0;i<str.size();i++){
        int pos = str[i]-'a';
        if(checker&(1<<pos)){
            return false;
        }
        checker |= (1<<pos);
    }
    return true;
}

If we can't use additional data structures, we can do the following:

1. Compare every character of the string to every other character of the string.This will take 0(n2) time and 0(1) space.

2. If we are allowed to modify the input string, we could sort the string in O(n log(n)) time and then linearly check the string for neighboring characters that are identical. Careful, though: many sorting algorithms take up extra space.

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/89736301
1.1