在微博上看到有人用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 False
def 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