Simple and clear python solution


  • 0
    Q
    class Solution:
    # @param haystack, a string
    # @param needle, a string
    # @return an integer
    def strStr(self, haystack, needle):
        ln = len(needle)
        lh = len(haystack)
        if ln > lh:
            return -1
        if ln == 0:#if needle is '' then return 0 for empty string is the substring of any string
            return 0
        for i in range(lh - ln + 1):#we only need consider the length of lh - ln
            j = 0
            while haystack[i + j] == needle[j]:
                j += 1
                if j == len(needle):
                    return i
        return -1

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.