CRCK: Array 1.1 (easy)

Cracking the Code interview 1.1: Implement an algorithm to determine if a string has all unique characters and what if you can't use additional data structures. 

(easy level)

// First with extra data structures.
// we can use a hashtable to remember the characters and a boolean to represent existing or not.
bool isUnique(string input) {
    // if the input string size equals to 0 or 1, there is no repeats.
    if(input.size() <= 1) return true;
    bool hashMap[256] = {false};
    for(int i = 0; i < input.size(); ++i) {
        if(hashMap[input[i]]) return false;
        hashMap[input[i]] = true;
    }
    return true;
}



If we are not allowed to use extra data structure. we will then need to confirm with the interviewer the encoding ways. UniCode or UTF-8, 32, 64 ?

// we are not allowed to use extra data structure. But we can use temporary value.
// The idea is simple:
// suppose the input ranges from 'a' to 'z' 'A' to 'Z' and we have input string: "abc"
// We use an integer's bits (64 bits) to remember whether the characters has showed up before.
// "abc" will be remembered by the integer as 0000...000111;
bool isUnique(string input) {
    // same as above, we need to check the length of input.
    if(input.size() <= 1) return true;
    int characters = 0;
    for(int i = 0; i < input.size(); ++i) {
        // if the bit have been turned into '1', there is a repeat.
        if(characters & (1 << int(input[i] - 'a'))) return false;
        // otherwise, we set the bit as 1.
        characters |= (1 << int(input[i] - 'a'));
    }
    return true;
} 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值