变位词检测

小白刷题第一天(LeetCode),欢迎大家批评指正(参考北京大学陈斌老师网易云课堂和python数据结构与算法分析第2版,其他资料均在文中指出)

数组/字符串部分

变位词检测(#242)

概念:如果一个字符串是另一个字符串的重新排列组合,那么这两个字符串互为变位词。(设定问题中的字符串长度相同,都是由26 个小写字母组成)

考虑到unicode字符采用ord()内置函数:ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。
菜鸟教程
1、计数法

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        c1 = [0] * 26
        c2 = [0] * 26
        for i in range(len(s)):
            pos = ord(s[i]) - ord('a')
            c1[pos] = c1[pos] + 1
        for i in range(len(t)):
            pos = ord(t[i]) - ord('a')
            c2[pos] = c2[pos] + 1

        j = 0
        stillOK = True
        while stillOK and j < 26:
            if c1[j] == c2[j]:
                j += 1
            else:
                stillOK = False
        return stillOK

2、标记比较法(清点法)

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        alist = list(s)
        pos1 = 0
        stillOK =True
        while pos1 < len(t) and stillOK:
            pos2 = 0
            found = False
            while pos2 < len(alist) and not found:
                if s[pos2] == t[pos1]:
                    found = True
                else:
                    pos2 += 1
            if found:
                alist[pos2] = None          # 不影响代码结果
            else:
                stillOK = False
        return stillOK

在力扣上超出时间限制
3、排序法

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        alist1 = list(s)
        alist2 = list(t)
        alist1.sort()
        alist2.sort()
        stillOK = True
        i = 0
        while i < len(s) and stillOK:
            if alist1[i] == alist2[i]:
                i += 1
            else:
                stillOK = False
        return stillOK

不适用于两个不等长的字符串
持更……(每个人都有潜在的能量,只是很容易被习惯所掩盖,被时间所迷离,被惰性所消磨。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值