变位词判断问题——Python实现

变位词判断问题——Python实现


变位词:如果两个单词存在相同字母的不同排列组合则称其为变位词。 例如:pythontyphon
目标:写一个布尔函数,以两个单词作为参数,返回这两个词是否为变位词。

解法一:逐字检查
逐一查看单词1中的字符是否能在单词2中找到

def anagramSolution1(s1,s2):
    alist=list(s2)#由于字符串是不可变类型,将s2复制到列表中
    pos1=0 #用来定位s1中的字符
    stillok=True
    while pos1 < len(s1) and stillok:#遍历s1
        pos2=0
        found=False
        while pos2 <len(alist) and not found: #遍历s2
            if s1[pos1]==alist[pos2]:
                found=True
            else:
                pos2+=1
        if found:
            alist[pos2]=None#找到字符,在对应的位置上打勾
        else:
            stillok=False
        pos1+=1
    return stillok
print(anagramSolution1('abcd','adbc'))

解法二:排序比较
先将两个字符串按字母的顺序排好,再逐个对比是否相同。这个算法中,主导其实是排序。`

def anagramSolution2(s1,s2):
    alist1=list(s1)#将两个字符串转换成两个列表
    alist2=list(s2)
    pos=0
    alist1.sort()#对两个列表中的字母进行排序
    alist2.sort()
    match=True
    while pos<len(s1) and match:#对排序后的列表进行逐个字符比较
        if alist1[pos]==alist2[pos]:
            pos+=1
        else:
            match=False
    return match
print(anagramSolution2('abcd','cdab'))

解法三:计数比较
为26个字母每一个都设置一个计数器,计数完成后再对比。这种方法的复杂度是最小的,只是存储空间需要的多一些。

```def anagramSolution3(s1,s2):
    c1=[0]*26#创建一个26位的计数器
    c2=[0]*26
    for i in range(len(s1)):
        pos=ord(s1[i])-ord('a')#ord函数用来返回26个字母的unicode数值,即确定这个字母的位置
        c1[pos]=c1[pos]+1#在相应的位数上加一
    for i in range(len(s2)):
        pos =ord(s2[i]) - ord('a')
        c2[pos] = c2[pos] + 1
    j=0
    stillok=True
    while j<26 and stillok:
        if c1[j]==c2[j]:
            j+=1
        else:
            stillok=False
    return stillok
print(anagramSolution3('abcd','dcba'))

python的collections库中其实有现成的函数来进行分位词的判断

from collections import Counter
def solution3(s1,s2):
    return Counter(s1)==Counter(s2)
print(solution3('abhy','dert'))
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值