CC189 - 1.1

博客围绕字符串唯一性判断展开,提及ASCII和unicode字符串相关知识,指出字符串长度超256无法形成唯一字符串。介绍了多种解法,如使用字符集数组、8个整数的数组、一个整数等,还给出在不能使用额外数据结构时的解决办法,包括双重比较和排序检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值