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