Cracking the coding interview--Q1.1(python的位操作)

来源:互联网 发布:mac 最大化 快捷键 编辑:程序博客网 时间:2024/05/01 08:21

在微博上看到有人用C++实现了一遍《Cracking the coding interview》上的题目。

自己目前正在学习python,也凑凑热闹。

1. 算法

题目 Cracking the coding interview--Q1.1
原文:Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
译文:实现一个算法来判断一个字符串中的字符是否唯一(即没有重复).不能使用额外的数据结构。 (即只使用基本的数据结构)

分析:很自然的想到用bitmap来做,但题目要求不使用自定义的数据结构。于是把bitmap的数据和操作分开,用8个int组成的buf来做位图的数据域。另外定义了一个testbit()和setbit()函数。

def testbit(buf, n):    index = n / 32    shift = n % 32    if (buf[index] & (1 << shift)):        return True    return Falsedef setbit(buf, n):    index = n / 32    shift = n % 32    buf[index] |= (1 << shift)def has_uniq_char(s):    assert isinstance(s, str)    buf = [0] * 32    for c in s:         if testbit(buf, ord(c)):            return False        setbit(buf, ord(c))     return True    if __name__ == "__main__":    print "abcd", has_uniq_char("abcd");    print "abcda", has_uniq_char("abcda");

本题的c++实现,可以参考:http://hawstein.com/posts/1.1.html


2. 相关知识

1.  python字符与数字互转
python提供了 两个函数来做字符与数字:
ord()将字符转数字; chr() 将数字转字符
注意:这里说的是字符和数字间的转换,而不是字符串。字符串和数字的转换,用string模块的atoi函数。

2. python的位操作
python的位操作与c/c++非常一致:
| 或 ; &与; ^异或;
检查一个数a第n位是否为1时,一般用a& (1<<n)
把数a第n位设置为1,一般用 a |= (1<<n)

3. python list操作
python不像c++ vector一样,可以把容器初始化为有n个相同的元素。
如:
vector<int> v(4, 100);
但是,可以用 *运算,来完成这个功能,如:
buf = [100] * 4;