Determine whether each is a character rearrangement
Given two strings s1 and s2, please write a program to determine whether the characters of one string can be changed into another string after the characters are rearranged.
Example 1:
- 输入: s1 = "abc", s2 = "bca"
- Output: true
Example 2:
- 输入: s1 = "abc", s2 = "bad"
- Output: false
Sample code 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)
Sample code 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)
Sample code 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)
running result:
Problem-solving ideas:
To learn more about the ord() function and chr() function in python, check the blog post: https://blog.csdn.net/weixin_44799217/article/details/112333924
To learn more about Python bitwise operators, check the blog post: https://blog.csdn.net/weixin_44799217/article/details/111715689
Sample code 1:
- Idea: bit operation
- Time complexity: O(N)
- Space complexity: O(1)
Sample code 3:
- Convert a string to a collection
- Take advantage of the non-repeatability of collection elements