码迷,mamicode.com
首页 > 其他好文 > 详细

基本数据结构之变位词三种解法

时间:2020-04-20 01:38:10      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:def   计数器   anagrams   app   ret   sort   apple   print   nlogn   

def anagramSolution1(s1, s2):
    """
    变位词第一种解法:O(n^2)
    :param s1:
    :param s2:
    :return:
    """
    alist = list(s2)  # s2字符串转换为列表
    pos1 = 0
    stillOK = True
    while pos1 < len(s1) and stillOK:  # 循环s1的每个字符
        pos2  = 0
        found = False
        while pos2 < len(alist) and not found:
            if s1[pos1] == alist[pos2]:  # 与s2元素逐个对比
                found = True
            else:
                pos2 += 1
        if found:
            alist[pos2] = None  # 找到,打钩
        else:
            stillOK = False  # 未找到,失败
        pos1 += 1
    return stillOK


print(anagramSolution1(‘python‘, ‘typhon‘))

def anagramSolution2(s1, s2):
    """
    变位词第二种解法:O(nlogn)
    :param s1:
    :param s2:
    :return:
    """
    alist = list(s1)
    blist = list(s2)
    alist.sort()  # 分别排序
    blist.sort()
    matches = True
    pos1 = 0
    while pos1 < len(alist) and matches:
        if alist[pos1] == blist[pos1]:  # 一一对比
            matches = True
        else:
            matches = False
        pos1 += 1
    return matches


print(anagramSolution2(‘abcd‘, ‘dcba‘))


def anagramSolution3(s1, s2):
    """
    变位词第三种解法,计数比较变位词:O(n)
    :param s1:
    :param s2:
    :return:
    """
    c1 = [0] * 26
    c2 = [0] * 26
    for i in range(len(s1)):
        pos = ord(s1[i]) - ord(‘a‘)  # 分别计数
        c1[pos] += 1
    for i in range(len(s2)):
        pos = ord(s1[i]) - ord(‘a‘)
        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(‘apple‘, ‘pleap‘))

基本数据结构之变位词三种解法

标签:def   计数器   anagrams   app   ret   sort   apple   print   nlogn   

原文地址:https://www.cnblogs.com/wsilj/p/12735172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!