Friedrich Ewald My Personal Website

Leetcode: String in String

A classic find the needle in the haystack problem. The task is to find if a string is contained within another string and return the index of the first position. If the string is not contained return -1 and if the needle is empty, return 0.

class Solution:
  def strStr(self, haystack: str, needle: str) -> int:
    if needle == "":
        return 0
    h = 0
    n = 0
    while h < len(haystack):
      if haystack[h] == needle[n]:
        n += 1
        h -= n
        n = 0
      h += 1
      if n == len(needle):
        return h - n
    return -1

if __name__ == '__main__':
  r = Solution().strStr
  print(r("mississippi", "issip"), 4)
  print(r("hello", 'll'), 2)
  print(r('a','a'), 0)

About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.