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

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


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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章