码迷,mamicode.com
首页 > 其他好文 > 详细

28. Implement strStr()

时间:2017-01-05 18:38:41      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:ret   color   stack   strstr   find   force   object   blog   class   

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

1

 

1 class Solution(object):
2     def strStr(self, haystack, needle):
3         """
4         :type haystack: str
5         :type needle: str
6         :rtype: int
7         """
8         return haystack.find(needle)

 

2 brute force

 

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        result = -1
        l_needle = len(needle)
        l_haystack = len(haystack)
        if l_needle == 0 and l_haystack == 0:
            return 0
        if l_haystack == 0 and l_needle!=0:
            return result    
        if l_needle == 0 :
            return 0
        for index in range(l_haystack):
            if l_haystack - index  >= l_needle and needle == haystack[index:index+l_needle]:
                result = index
                break
        return result 

 

28. Implement strStr()

标签:ret   color   stack   strstr   find   force   object   blog   class   

原文地址:http://www.cnblogs.com/rocksolid/p/6244541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!