描述
给一串名字,将他们去重之后返回。两个名字重复是说在忽略大小写的情况下是一样的。
您在真实的面试中是否遇到过这个题? 是
说明
你可以假设名字只包含大小写字母和空格。
样例
给出:
[
"James",
"james",
"Bill Gates",
"bill Gates",
"Hello World",
"HELLO WORLD",
"Helloworld"
]
返回:
[
"james",
"bill gates",
"hello world",
"helloworld"
]
返回名字必须都是小写字母。
实现代码:
用基数转换法定义一个哈希函数,把字符串映射到相应下标
class Solution: """ @param names: a string array @return: a string array """ def nameDeduplication(self, names): # write your code here #定义一个字典 self.hash_str = {} # 定义字典的长度,等于数组长度 HASH_SIZE = len(names) for str in names: temp = str.lower() self.hash_str[self.hashCode(temp, HASH_SIZE)] = temp return sorted(self.hash_str.values()) #定义一个哈希函数 def hashCode(self, val, HASH_SIZE): key = 0 for x in val: key = (key * 31 + ord(x)) % HASH_SIZE #对冲突进行处理 if key in self.hash_str.keys(): #当前哈希表中的值和要存入的值不同时,向后延顺 #如果当前key对应的哈希表没有值时会报错,所以用try处理 try: while self.hash_str[key] != val: key += 1 except: pass return key
用python自带的字典,直接将值作为key
class Solution: """ @param names: a string array @return: a string array """ def nameDeduplication(self, names): # write your code here set1 = set() for name in names: set1.add(name.lower()) return list(set1)