题目:求解字符串是否是回文串或者镜像串(回文串是指正序逆序都一样,镜像串是指镜像后字符串一样),其中,镜像字典如下:
{'A':'A', 'E':'3', 'H':'H', 'I':'I', 'J':'L', 'L':'J',
'M':'M', 'O':'O', 'S':'2', 'T':'T', 'U':'U', 'V':'V',
'W':'W', 'X':'X', 'Y':'Y', 'Z':'5','1':'1','2':'S','5':'Z','8':'8'}
直接上代码吧,也很简单。
"""
输入一个字符串,判断是否是回文串或者镜像串
算法竞赛入门经典(第2版)
P48例题3-3
"""
#coding:utf-8
def huiwenchuan(string):
return string == string[::-1]
def jingxiangchuan(string, dt):
isjingxiangchuan = False
for i in range(0,len(string)//2):
if string[i] in dt.keys() and (string[len(string)-1-i] in dt[string[i]]):
isjingxiangchuan = True
else:
isjingxiangchuan = False
return isjingxiangchuan
if __name__ == '__main__':
string = "madam"
#回文串
print(huiwenchuan(string))
#镜像串
#string = '2A3MEBS'
dt = {'A':'A', 'E':'3', 'H':'H', 'I':'I', 'J':'L', 'L':'J',
'M':'M', 'O':'O', 'S':'2', 'T':'T', 'U':'U', 'V':'V',
'W':'W', 'X':'X', 'Y':'Y', 'Z':'5','1':'1','2':'S','5':'Z','8':'8'}
print(jingxiangchuan(string=string, dt=dt))
Ref:
算法竞赛入门经典第二版