数据结构与算法之一个乱序字符串检查的例子

解法一

检查第一个字符串是不是出现在第二个字符串中,如果可以检查到每一个字符,那么则乱序。由于Python字符串是不可变的,所以第一步是将第二个字符串转换成列表。再检查第一个字符串中每个字符是否存在于第二个列表里。

def anagramSolution1(s1,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]:
                    found = True
                else:
                    pos2 = pos2 + 1
            if found:
                    alist[pos2] = None
            else:
                    stillOK = False
            pos1 = pos1 + 1
    return stillOK

print(anagramSolution1('abcd','dcba'))  #True


#测试结果
>>> print(anagramSolution('abcd','dcbea'))
True
>>> print(anagramSolution('abecd','dcba'))
False

 

 S1中的每个字符在S2中最多进行N个字符的比较,算法复杂度O(n^2)

 

解法二:排序和比较

按照字母顺序从a到z排列字符串,如果两个字符串相同,那么互为乱序字符串。

def anagramSolution2(s1,s2):
    alist1 = list(s1)
    alist2 = list(s2)
    
    alist1.sort()
    alist2.sort()
    pos = 0
    matches = True
    while pos < len(s1) and matches:
        if alist1[pos]==alist2[pos]:
            pos = pos + 1
        else:
            matches = False
    return matches

#测试

>>> print(anagramSolution2('abc','adcb'))
True

>>> print(anagramSolution2('abdc','acb'))

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    print(anagramSolution2('abdc','acb'))
  File "C:/Users/y/Desktop/test.py", line 13, in anagramSolution2
    if alist1[pos] == alist2[pos]:
IndexError: list index out of range
>>> 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值