算法分析2.4-乱序字符串检查

来源:https://legacy.gitbook.com/book/xidianwlc/python-data-structrue-and-algrothms/details

参考学习,代码改进 

2.4.一个乱序字符串检查的例子

#python
#查询s2中是否包含s1中的的字母是否相同
def anagramSolution1(s1,s2):
    print(type(s1))
    print(type(s2))
    alist=list(s2) #将元组转变为列表
    pos1=0
    stillOk=True
    while pos1<len(s1) and stillOk:
        pos2=0
        found=False
        while pos2<len(alist) and not found:  #当存在字母相同时,跳出循环 或不存在相同时跳出循环
            if s1[pos1]==alist[pos2] and pos2==len(s1)-pos1-1:  #加上pos2==len(s1)-pos1-1为回文判断
                found=True                    #判定条件
            else:
                pos2=pos2+1
        if found:
            alist[pos2]=None
        else:
            stillOk=False
        pos1=pos1+1
        
    return stillOk

print(anagramSolution1('abcd','abdc'))
print(anagramSolution1('abcd','d'))




#查询s2中是否包含s1中的的字母是否相同,排序后筛选
def anagramSolution2(s1,s2):
    alist1=list(set(s1))  #set()去重
    alist2=list(set(s2))
    alist1.sort()
    alist2.sort()
    print(alist1,alist2)
    pos=0
    matches=True
    while pos<len(alist1) and matches: #len(alist1)计算alist1的长度,当s1=s2否者会报错
        if alist1[pos]==alist2[pos]:
            pos=pos+1
        else:
            matches=False
    return matches
print(anagramSolution2('abcdss','abcdddwdss'))
print(anagramSolution2('asbscde','asbscde'))

#计数和比较,s1 s2字母相同,且个数相同,排序不同
c1=[0]*26

   
def anagramSolution4(s1,s2):
    c1=[0]*26
    c2=[0]*26
    for i in range(len(s1)):  #计算每个字母出现的次数
        pos=ord(s1[i])-ord('a') #ord()返回对应的 ASCII 数值,或者 Unicode 数值 计算与a数值大小
        c1[pos]=c1[pos]+1

    for i in range(len(s2)):
        pos=ord(s2[i])-ord('a')
        c2[pos]=c2[pos]+1
    print(c1,c2)
    j=0
    stillOK=True
    while j<26 and stillOK:  #比较字母出现个数数量是够相同
        if c1[j]==c2[j]:
            j=j+1
        else:
            stillOK=False
    return stillOK
print(anagramSolution4('appleppp','pleapppp'))

  

原文地址:https://www.cnblogs.com/papio/p/9448020.html