题目:
Code:
- 法1 (最简单直观)
n=input().split()
c=n[0]
d=n[1]
if len(c)>=len(d):
a=c+c
b=d
else:
a=d+d
b=c
if b in a:
print("true")
else:
print("false")
- 法2 (这个是我第一次做的时候写的,太麻烦)
s1,s2=map(str,input().split())
is_right=0
if len(s1)<len(s2):
s0=s1
s1=s2
s2=s0
for i in range(len(s1)):
word=""
for j in range(len(s2)):
s0=s1[(i+j)%len(s1)]
word+=s0
if word==s2:
is_right+=1
if is_right==0:
print(("false"))
else:
print("true")
- 法3 (老师给的代码,我给优化成法1了)
n=input().split()
c=n[0]
d=n[1]
if len(c)>=len(d):
a=list(c)
b=list(d)
else:
a=list(d)
b=list(c)
import copy
aa=copy.deepcopy(a)
for i in aa:
a.append(i)
a="".join(a)
b="".join(b)
if b in a:
print("true")
else:
print("false")
解题思路:
如果s1的长度小于s2的长度,则交换s1和s2的值,保证s1是较长的字符串。
使用两个嵌套的循环。外部循环根据s1的长度遍历每个字符,内部循环根据s2的长度遍历每个字符。
在每次内部循环中,根据循环移位规则,将s1中的字符逐个拼接形成新的字符串word。
每次拼接后,判断word是否与s2相等,如果相等,则将is_right加1。
循环结束后,根据is_right的值进行判断,如果为0,则说明s2不是通过循环移位得到的新字符串的子串,输出"false";否则输出"true"。
奇技淫巧:
- 判断字符串1是否包含在字符串2中,直接用
in
就可以了; map(type,input().split(*))
可以直接分别赋值给多个变量;import copy
后注意浅拷贝copy.copy(x)
和深拷贝copy.deepcope(x)
的区别;"".join(x)
可以把列表中分开的字符合成一整个字符串