それぞれが文字の再配置であるかどうかを判別します
2つの文字列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:
- 文字列をコレクションに変換する
- コレクション要素の非再現性を活用する