判定是否互为字符重排

last modify

问题简述

判定给定的两个字符串是否互为字符重排。
详细描述
给定两个字符串 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路1:哈希表

Python
class Solution:
    def CheckPermutation(self, s1: str, s2: str) -> bool:
        if len(s1) != len(s2): return False
        
        cnt = [0] * 128
        for c1, c2 in zip(s1, s2):
            cnt[ord(c1)] += 1  # ord 函数用于获取字符的 ascii 码值
            cnt[ord(c2)] -= 1

        return not any(cnt)

思路2:排序

Python
class Solution:
    def CheckPermutation(self, s1: str, s2: str) -> bool:
        return sorted(s1) == sorted(s2)

Last updated