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'))
    

      

  • 相关阅读:
    开源项目
    [Accessibility] Missing contentDescription attribute on image [可取行]失踪contentDescription属性图像
    Android 布局 中实现适应屏幕大小及组件滚动
    EF 错误记录
    EasyUI 加载时需要显示和隐藏 panel(面板)内容破版问题
    IE 报表缩放后页面破版
    VS 2017 引入nuget 问题
    SSRS 报表显示页面 asp net session丢失或者找不到 asp net session has expired or could not be found()
    log4net 配置
    网站
  • 原文地址:https://www.cnblogs.com/papio/p/9448020.html
Copyright © 2011-2022 走看看