首页 > 编程语言 > 详细

Leetcode 28.实现strStr() By Python

时间:2018-09-22 11:45:37      阅读:132      评论:0      收藏:0      [点我收藏+]

思路

如果不用python自带的索引功能,就要遍历的时候进行比较,用切片会很方便

可以偷个懒用python的索引功能

代码

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        try:
            haystack.index(needle)
            return haystack.index(needle)
        except ValueError:
            if len(needle) == 0 :
                return 0
            else:
                return -1
        

改进

index()方法会抛出异常,该用find()方法就不用考虑,find()方法失败的时候会返回-1

Leetcode 28.实现strStr() By Python

原文:https://www.cnblogs.com/MartinLwx/p/9689535.html

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