This is a clean brute-force algorithm. We can traverse all the possible starting points of haystack(from 0to
haystack.length() - needle.length()) and see if the following characters in haystackmatch those of needle.
Special cases:
Both haystack and needle can be empty. If haystack is empty, needle is not, should return -1. If needle is empty, haystack is not, should return 0. If both empty, should return 0.
Code 1:
classSolution(object):defstrStr(self,haystack,needle):""" :type haystack: str :type needle: str :rtype: int """for i inrange(len(haystack) -len(needle)+1):if haystack[i:i+len(needle)]== needle:return ireturn-1
Code 2:
classSolution(object):defstrStr(self,haystack,needle):""" :type haystack: str :type needle: str :rtype: int """iflen(needle)==0:return0iflen(haystack)==0:return-1for i inrange(len(haystack) -len(needle) +1):for j inrange(len(needle)):if haystack[i + j]!= needle[j]:breakelse:# when no break is triggered in the previous for loopreturn ireturn-1