问题:查找字符串b在a中的起始位置,如果b不为a的子串,则返回-1
示例:
输入:a = "well", b = "el" 输出:1
输入:a="alpha", b = "am" 输出:0
Python代码:
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 n_len = len(needle) h_len = len(haystack) if n_len > h_len: return -1 elif n_len == h_len: if haystack == needle: return 0 return -1 for i in range(h_len-n_len+1): if haystack[i:i+n_len] == needle: return i return -1