文字列の回転
2つの文字列s1とs2が与えられた場合、s2がs1によって回転されているかどうかを確認するコードを記述してください(たとえば、waterbottleはerbottlewatの回転された文字列です)。
例1:
- 輸入入:s1 = "waterbottle"、s2 = "erbottlewat"
- 出力:True
例2:
- 取入:s1 = "aa"、s2 = "aba"
- 出力:False
サンプルコード1:
class Solution(object):
def isFlipedString(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if len(s1) != len(s2):
return False
s3 = s1 + s1
return s2 in s3
# s1 = "waterbottle"
# s2 = "erbottlewat"
s1 = "aa"
s2 = "aba"
a = Solution()
b = a.isFlipedString(s1, s2)
print(b)
サンプルコード2:
class Solution(object):
def isFlipedString(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
return len(s1) == len(s2) and s2 in s1 * 2
# s1 = "waterbottle"
# s2 = "erbottlewat"
s1 = "aa"
s2 = "aba"
a = Solution()
b = a.isFlipedString(s1, s2)
print(b)
実行結果:
アイデア分析:
方法1:
s2を2倍にし、長さが同じ場合、s1はs3の部分文字列である必要があります
複雑さの分析
- 時間計算量:O(N)
- スペースの複雑さ:O(N)