zoukankan      html  css  js  c++  java
  • 基本数据结构之变位词三种解法

    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'))
    
  • 相关阅读:
    ViewPager自动轮播、小圆点切换
    android自定义view属性
    单点触控
    自定义view、自定义圆形imageview
    为textview中的字符串着色
    xstream解析、httputils请求
    WebView加载页面
    HorizontalScrollView滑动 ViewPager切换
    Spring Boot 热部署(IDEA与Gradle)
    Linux下安装JDK
  • 原文地址:https://www.cnblogs.com/wsilj/p/12735172.html
Copyright © 2011-2022 走看看