判定是否互为字符重排

判定是否互为字符重排

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

示例 1:

  • 输入: s1 = "abc", s2 = "bca"
  • 输出: true 

示例 2:

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

示例代码1:

#  位运算
class Solution(object):
    def CheckPermutation(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        if len(s1) != len(s2):
            return False
        res = 0
        for i in range(len(s1)):
            res += 1 << ord(s1[i])
            res -= 1 << ord(s2[i])
        return res == 0


a = Solution()
# b = a.CheckPermutation('abc', 'bca')
b = a.CheckPermutation('abd', 'bca')
print(b)

示例代码2:

#  字符串排序后比较
class Solution(object):
    def CheckPermutation(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        return sorted(s1) == sorted(s2)


a = Solution()
b = a.CheckPermutation('abc', 'bca')
# b = a.CheckPermutation('abd', 'bca')
print(b)

示例代码3:

#  利用集合元素的不可重复性
class Solution(object):
    def CheckPermutation(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        return set(s1) == set(s2)


a = Solution()
# b = a.CheckPermutation('abc', 'bca')
b = a.CheckPermutation('abd', 'bca')
print(b)

运行效果:

解题思路:

详细了解python 中的ord()函数和chr()函数,查看博文:https://blog.csdn.net/weixin_44799217/article/details/112333924

详细了解Python 位运算符,查看博文:https://blog.csdn.net/weixin_44799217/article/details/111715689

示例代码1:

  • 思路:位运算
  • 时间复杂度: O(N)
  • 空间复杂度: O(1)

示例代码3:

  1. 将字符串转为集合
  2. 利用集合元素的不可重复性
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值