首页 > 其他 > 详细

查找字符串b在a中的起始位置,如果b不为a的子串,则返回-1

时间:2019-04-10 10:56:11      阅读:197      评论:0      收藏:0      [点我收藏+]

示例:

输入: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
                

 

查找字符串b在a中的起始位置,如果b不为a的子串,则返回-1

原文:https://www.cnblogs.com/wenqinchao/p/10681947.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!