【Cracking the coding interview】Q1.1(字符唯一)

来源:互联网 发布:配置网络 ubuntu 编辑:程序博客网 时间:2024/05/01 12:28
读了Hawstein大神的大作,读书笔记记录之,膜拜大神用,给自己增些知识。

Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

实现一个算法来判断一个字符串中的字符是否唯一

思路:用最小的数组或者是用位运算来实现。acii的字符用256位来记录就够了。

bool a[256]; if(a[i]) return false;else return true;

如果只有小写字母用一个int就可以了,这里涉及到位运算

bool isUnique(string s){    int check = 0;    int len = s.length();    for(int i=0; i<len; ++i)    {        int v = (int)(s[i]-'a');        if(check & (1<<v)) return false;        check |= (1<<v);    }    return true;}

更多大神的著作参见这里 http://hawstein.com/posts/1.1.html


0 0