分析:哈希法。
code:
(1)
strs = 'Good'
hashTable = dict()
listStrs = list(strs)
i = 0
while i <len(strs):
if listStrs[i] in hashTable:
print("有重复字符")
break
else:
hashTable[listStrs[i]] = None
i += 1
if i >= len(strs):
print("没用重复字符")
break
程序运行结果:
有重复字符
(2)
def longest_repetition(chars):
if len(chars) is None or len(chars) <= 1:
return (chars, len(chars))
result = [1] * len(chars)
for left in range(len(chars) - 1):
for right in range(left + 1, len(chars)):
if chars[left] == chars[right]:
print("a")
result[left] += 1
else:
print("aa")
break
#return result
return (chars[result.index(max(result))], max(result))
if __name__ == "__main__":
txt = 'banaaana'
print(longest_repetition(txt))
题目:给定由字母组成的字符串s1和s2,其中,s2中字母的个数少于s1,如何判断s1是否包含s2?
分析:哈希法。
code:
str1 = 'aaaabbce'
str2 = 'abcbbaaad'
list1 = list(str1)
list2 = list(str2)
i = 0
hashTable1 = dict()
while i <len(str1):
if list1[i] not in hashTable1:
hashTable1[list1[i]] = 0
i += 1
i = 0
hashTable2 = dict()
while i <len(str2):
if list2[i] not in hashTable2:
hashTable2[list2[i]] = 0
i += 1
count = 0
for k, v in hashTable1.items():
if k in hashTable2:
count += 1
else:
print("不包含")
break
程序运行结果:
不包含
第一种方法:使用正则表达式判断字符串是否包含字母
第二种方法:使用isalpha()。是字母的时候返回True,不是字母的时候返回False,
原文至:https://www.py.cn/faq/python/12102.html