简体   繁体   中英

Leetcode 28 Question - Why is my strStr() failing?

I am attempting to solve this leetcode question: https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/885/

The idea is that you write code that can find a substring within a string. For the sake of practice, I am (or atleast was) trying to do this in the most efficient way possible. I figured it can be done in one "for" loop (hopefully only taking O(n) time)

This is my code

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        needle = list(needle)
        haystack = list(haystack)
        goodPos = None
        goodCounter = 0
        if len(needle) == 0:
            return 0
        if len(haystack) == 0 or len(needle) > len(haystack):
            return -1
        for key, value in enumerate(haystack):
            if needle[goodCounter] != value:
                print(f"{needle[goodCounter]} does not match {value}, resetting")
                goodPos = None
                goodCounter = 0
            if needle[goodCounter] == value:
                print(f"We have a match at {value}")
                if goodCounter == 0:
                    print(f"We are setting the key at {key}")
                    goodPos = key
                goodCounter += 1
            if len(needle) == goodCounter:
                return goodPos
        print("Finished for loop")
        print(f"goodPos at {goodPos}")
        print(f"goodCounter at {goodCounter}")
        #For situations where we didnt caught it
        if goodCounter == len(haystack):
            return len(haystack)
        return -1

I am stuck on 73 / 79 test cases passed. Specifically with this input

Input: "mississippi" (substring: "issip")
My output: -1
Expected Output: 4

I am kind of stuck why my code is not working.

Here is what I get when I run your code:

key,value,goodPos,goodCounter
0  ,m    ,None   ,0
1  ,i    ,None   ,0
2  ,s    ,1      ,1
3  ,s    ,1      ,2
4  ,i    ,1      ,3
5  ,s    ,1      ,4
6  ,s    ,None   ,0
7  ,i    ,None   ,0
8  ,p    ,7      ,1
9  ,p    ,None   ,0
10 ,i    ,None   ,0

They key keeps getting incremented and by the time it realizes that keyPos = 1 is not a complete match, the key has already been set to position 7 and by then it's too late to find a match. I think you need a nested for loop.

Edit:

I decided to take a stab at it myself and here's the for loop I came up with:

    for key, value in enumerate(haystack):
        if needle[0] == value:
            goodPos = key
            for key, value in enumerate(needle):
                if (len(haystack) - goodPos) < len(needle):
                    print('Needle went past end of haystack. No match found')
                    return -1
                if value == haystack[goodPos + key]:
                    goodCounter += 1
                    if len(needle) == goodCounter:
                        print('Match found at goodPos = ', goodPos)
                        return goodPos
                else:
                    goodCounter = 0
        else:
            goodPos = ''
            goodCounter = 0
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        result = -1
        try :
            result = haystack.index(needle)
        except:
            result = -1
        return result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM