Why my code doesn't work


  • 0
    Y

    I am using the following code to solve this problem

            ans = list()
            pcnt = collections.Counter(p)
            for i in range(len(s)):
                if collections.Counter(s[i:i+len(p)]) == pcnt:
                    ans.append(i)
            return ans
    

    It gives me time exceeded error. However the following code works fine:

            ls, lp = len(s), len(p)
            cp = collections.Counter(p)
            cs = collections.Counter()
            ans = []
            for i in range(ls):
                cs[s[i]] += 1
                if i >= lp:
                    cs[s[i - lp]] -= 1
                    if cs[s[i - lp]] == 0:
                        del cs[s[i - lp]]
                if cs == cp:
                    ans.append(i - lp + 1)
            return ans
    

    Can anyone help me by explaining why using a Counter in the first solution doesn't work but in the second solution works?


Log in to reply
 

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