【面试题 01.02. 判定是否互为字符重排】

【面试题 01.02. 判定是否互为字符重排】,第1张

【面试题 01.02. 判定是否互为字符重排】

给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。

示例 1:

输入: s1 = "abc", s2 = "bca"
输出: true 
示例 2:

输入: s1 = "abc", s2 = "bad"
输出: false
说明:

0 <= len(s1) <= 100
0 <= len(s2) <= 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-permutation-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法一:遍历

创建一个26大小的数组来存放每个字母出现的次数,遍历s1数组,遇到一个字符就对相应位置的值做+1 *** 作,然后遍历s2数组,做相反的-1 *** 作,如果遍历完之后数组存在值为1,那么返回false,否则返回true

class Solution:
    def CheckPermutation(self, s1: str, s2: str) -> bool:
        tem=[0]*27
        for i in s1:
            tem[ord(i)-97]+=1
        for i in s2:
            tem[ord(i)-97]-=1
        for i in range(26):
            if tem[i]!=0:
                return False
        return True

方法二:哈希表(字典)

这里学到一个python中字典的用法,collections.defaultdict() 类,可指定所有 key 对应的默认 value ,用法参考:python中defaultdict用法详解 - 简书

class Solution:
    def CheckPermutation(self, s1: str, s2: str) -> bool:
        if len(s1) != len(s2):
            return False
        dic = defaultdict(int)
        for i in s1:
            dic[i] += 1
        for i in s2:
            dic[i] -= 1
        for val in dic.values():
            if val != 0:
                return False
        return True

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5720384.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-18
下一篇2022-12-18

发表评论

登录后才能评论

评论列表(0条)

    保存