查找字符串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
                

 

上一篇:经典SQL语句大全


下一篇:LeetCode 初级算法题(字符串)7.实现strStr()