0%

13.字符串查找

13.字符串查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
"""
@param source:
@param target:
@return: return the index
"""
def strStr(self, source, target):
geshu=0
a = len(source)
b = len(target)
if source =="" and target =="":#排除特殊情况
return 0
elif source !="" and target =="":#继续排除特殊情况
return 0
elif target not in source:#被查找字符串不在已知字符串的情况
return -1
else:#需要返回第一个出现位置的情况
for i in range(a):
if target[0] == source[i]:
for j in range(b):
if (i+j) < a:#避免字符串索引溢出
if source[i+j] == target[j]:
geshu = geshu + 1

if geshu == b:
return i

so = Solution()
print(so.strStr("tartarget","target"))