要求:
“对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。 如果不存在,则返回 -1。
1.使用find()实现
def strstr(source,target): if (source is None) or (target is None): return -1 elif source.find(target) >= 0: return source.find(target) elif target.find(source) >= 0: return target.find(source) else: return -1 print(strstr('source', 'target')) print(strstr('abcdabcdefg', 'cde')) print(strstr('abcd', 'abcdabcdefg'))
2.使用idex()实现
1 def strstr(source,target): 2 try: 3 if (source is None) or (target is None): 4 return -1 5 elif source.index(target) >= 0 : 6 return source.index(target) 7 elif target.index(source) >= 0: 8 return target.index(source) 9 except ValueError: 10 return -1 11 12 13 print(strstr('source', 'target')) 14 print(strstr('abcdabcdefg', 'cde')) 15 print(strstr('abcd', 'abcdabcdefg'))
3.利用两者的位数差
1 def strstr(source, target): 2 if (source is None) or (target is None): 3 return -1 4 for i in range(len(source) - len(target) + 1): 5 if source[i:i + len(target)] == target: 6 return i 7 return -1 8 9 print(strstr('source', 'target')) 10 print(strstr('abcdabcdefg', 'bcd'))
浙公网安备 33010602011771号