close

Implement strStr().

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


class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle) > len(haystack):
            return -1
        if len(needle) == 0:
            return 0
        for x in xrange(len(haystack) - len(needle) + 1):
            if haystack[x] == needle[0]:
                for y in xrange(1, len(needle) + 1):
                    if y == len(needle):
                        return x
                    if haystack[x+y] != needle[y]:
                        break
        return -1

PYTHONIC WAY:

return haystack.find(needle)


 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 g0d2 的頭像
    g0d2

    kazi1@的部落格

    g0d2 發表在 痞客邦 留言(0) 人氣()