zoukankan      html  css  js  c++  java
  • 算法分析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'))
    

      

  • 相关阅读:
    客户端rsyslog配置文件详解
    logstash插件配置-codec插件说明json和multiline
    Linux流量监控工具
    单线程 Redis 为什么这么快,看看这篇就知道了
    RabbitMQ Network Partitions 处理策略
    inux 下配置网卡的别名即网卡子IP的配置 转
    Prometheus的监控解决方案(含监控kubernetes)
    Prometheus+Grafana监控Kubernetes
    python输入一维数组(输入以空格为间隔的一行)
    用gdb来理解:值传递/指针传递/引用传递
  • 原文地址:https://www.cnblogs.com/papio/p/9448020.html
Copyright © 2011-2022 走看看