Cracking the coding interview--Q1.1(python的位操作)
2013-07-09 10:57
543 查看
在微博上看到有人用C++实现了一遍《Cracking the coding interview》上的题目。
自己目前正在学习python,也凑凑热闹。
原文: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()函数。
本题的c++实现,可以参考:http://hawstein.com/posts/1.1.html
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;
自己目前正在学习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;
相关文章推荐
- 《Cracking the Coding Interview》——第5章:位操作——题目7
- 《Cracking the Coding Interview》——第5章:位操作——题目8
- Cracking the coding interview--Q1
- 【Cracking the coding interview】Q1.7(矩阵置0)
- 【Cracking the coding interview】Q1.8(旋转字符串)
- 《Cracking the Coding Interview》——第5章:位操作——题目1
- 【Cracking the coding interview】Q1.4(变位词)
- 《Cracking the Coding Interview》——第5章:位操作——题目2
- 【Cracking the coding interview】Q1.1(字符唯一)
- 《Cracking the Coding Interview》——第5章:位操作——题目3
- 《Cracking the Coding Interview》——第5章:位操作——题目4
- 《Cracking the Coding Interview》——第5章:位操作——题目5
- 《Cracking the Coding Interview》——第5章:位操作——题目6
- 【Cracking the coding interview】Q1.6(旋转矩阵)
- Cracking the Coding Interview Q1.5
- Cracking the coding interview: 查找文中两个单词的距离
- cracking the coding interview No1.8
- Cracking the coding interview--Q1.5
- Cracking the coding interview--Q9.7
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目3