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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值