:type haystack: str :type needle: str :rtype: int
(self, haystack, needle)
| 41 | """ |
| 42 | class Solution(object): |
| 43 | def strStr(self, haystack, needle): |
| 44 | """ |
| 45 | :type haystack: str |
| 46 | :type needle: str |
| 47 | :rtype: int |
| 48 | """ |
| 49 | # bulit-in 20ms |
| 50 | # return haystack.find(needle) |
| 51 | |
| 52 | # myself |
| 53 | if not needle: |
| 54 | return 0 |
| 55 | |
| 56 | # 24ms. |
| 57 | lengthHaystack = len(haystack) |
| 58 | lengthNeedle = len(needle) |
| 59 | |
| 60 | if lengthNeedle > lengthHaystack: |
| 61 | return -1 |
| 62 | |
| 63 | if lengthNeedle == lengthHaystack: |
| 64 | return 0 if haystack == needle else -1 |
| 65 | |
| 66 | for i, d in enumerate(haystack): |
| 67 | if lengthHaystack - i < lengthNeedle: |
| 68 | return -1 |
| 69 | |
| 70 | if d == needle[0]: |
| 71 | if haystack[i:i+lengthNeedle] == needle: |
| 72 | return i |
| 73 |
nothing calls this directly
no outgoing calls
no test coverage detected