字符串之间的关系
字符串的包含关系
牛客网:字符串的包含关系
题目描述
我们定义字符串包含关系:字符串A=abc,字符串B=ab,字符串C=ac,则说A包含B,A和C没有包含关系。
输入描述:
两个字符串,判断这个两个字符串是否具有包含关系,测试数据有多组,请用循环读入。
输出描述:
如果包含输出1,否则输出0.
思路:
遍历长的字符串,当
l
o
n
g
[
i
]
=
s
h
o
r
t
[
0
]
long[i]=short[0]
long[i]=short[0] 时,可以采用循环遍历,依次比对long字符串 i 后面的字符和 short 后面的字符。如果循环顺利终止,必定将short完整循环了一次,由此可判定有包含关系。如果提前终止,说明只匹配了部分字符串,那么我们要再从long字符串的 i+1 位置开始继续遍历比对。
这里可以在while循环中加入一个判断语句,可以提前终止循环。那就是
l
e
n
(
s
h
o
r
t
)
−
j
<
=
l
e
n
(
l
o
n
g
)
−
i
len(short)-j <= len(long)-i
len(short)−j<=len(long)−i
这个语句的意思是:long字符串自比对的首项开始到结尾字符的长度,至少要大于short整个字符的长度。
import sys
def include(str1,str2):
if len(str1)<len(str2):
long = str2
short = str1
else:
long = str1
short = str2
i,j = 0,0
while i < len(long) and len(short)-j <= len(long)-i:
temp = i
while temp < len(long) and j < len(short) and long[temp]==short[j]:
temp += 1
j += 1
if j==len(short):
return True
else:
i += 1
j = 0
return False
for line in sys.stdin:
t = list(line.split())
if include(t[0],t[1]):
print(1)
else:
print(0)