题目:对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
。
思路:很简单,看代码就能懂(Python处理字符真的优势很大),主要是注意一些细节
链接:点击打开链接
代码:
class Solution:
"""
@param: source: source string to be scanned.
@param: target: target string containing the sequence of characters to match
@return: a index to the first occurrence of target in source, or -1 if target is not part of source.
"""
def strStr(self, source, target):
# write your code here
if(source==None)or(target==None) :
return -1
else:
if target in source:
return (source.index(target))
else:
return (-1)