return len(s)

        h, t = [], []
        recent, overall = 0, 0
        for i in xrange(len(s)):
            if len(h) == 0 or (len(h) == 1 and s[i] != s[h[0]]):
                h.append(i)
                t.append(i)
            elif s[i] == s[h[0]]:
                t[0] = i
            elif s[i] == s[h[1]]:
                t[1] = i
            else:
                h = [min(t) + 1, i]
                t = [max(t), i]
            recent = t[0] - h[0] + 1 if len(h) == 1 else max(t) - min(h) + 1
            overall = max(recent, overall)
            #print h, t, recent, overall
        return overall


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = ["eceba", "aba"]
    answers = [3, 3]
    test(Solution().lengthOfLongestSubstringTwoDistinct, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        recent = [(nums[0], 0)] if nums[0] >= 0 else [(0, nums[0])]
        overall = [(x, y) for (x, y) in recent]

        pos, neg = recent[-1]
        for i in xrange(1, len(nums)):
            tmp_pos = nums[i] if not pos else pos * nums[i]
            tmp_neg = 0 if not neg else neg * nums[i]
            pos, neg = (tmp_pos, tmp_neg) if nums[i] >= 0 else (tmp_neg,
                                                                tmp_pos)

            recent.append((pos, neg))
            pos_all, neg_all = overall[-1]
            if pos and pos_all < pos:
                pos_all = pos
            if neg and neg_all > neg:
                neg_all = neg
            overall.append((pos_all, neg_all))
            #print recent, overall
        return overall[-1][0]


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [[0, 2], [2, 3, -2, 4], [-2, 0, -1]]
    answers = [2, 6, 0]
    test(Solution().maxProduct, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #3
0
                    child = child.next
                parent = parent.next
            parent = dummy.next
            child = dummy
            dummy.next = None

        return write(root)


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    m = 4
    n = 2**m - 1
    nums = range(n)
    nodes = [TreeLinkNode(x) for x in nums]
    root = nodes[0]
    for i in xrange(n / 2):
        nodes[i].left = nodes[2 * i + 1]
        nodes[i].right = nodes[2 * (i + 1)]

    nodes[2].left = None

    #print root, root.left, root.left.next, root.right
    arguments = [root]
    answers = [nums[:5] + nums[6:11] + nums[13:]]
    test(Solution2().connect, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        if not haystack or len(needle) > len(haystack):
            return -1

        pi = 0
        while len(haystack) - pi >= len(needle):
            if haystack[pi] == needle[0]:
                i, j = pi, 0
                while haystack[i] == needle[j]:
                    i += 1
                    j += 1
                    if j == len(needle):
                        return pi
            pi += 1
        return -1


if __name__ == "__main__":
    from leetcodelib import test
    arguments = [('ab', 'a'), ('baab', 'aa'), ('baab', 'abc')]
    answers = [0, 1, -1]
    test(Solution().strStr, arguments, answers)
Exemple #5
0
        :type str: List[str]
        :rtype: void Do not return anything, modify str in-place instead.
        """
        self.reverse(str, 0, len(str) - 1)
        h = 0
        for t in xrange(len(str)):
            if str[t] == ' ':
                self.reverse(str, h, t - 1)
                h = t + 1
            elif t == len(str) - 1:
                self.reverse(str, h, t)

    def reverse(self, str, i, j):
        while i < j:
            str[i], str[j] = str[j], str[i]
            i += 1
            j -= 1


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arg = 'the sky is blue'
    ans = 'blue is sky the'
    arguments = [list(arg)]
    answers = [list(ans)]
    test(Solution().reverseWords, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        res = m
        for i in xrange(m + 1, n + 1):
            res &= i
        return res


class Solution3(object):
    def rangeBitwiseAnd(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        count = 1
        while m != n:
            count <<= 1
            m >>= 1
            n >>= 1
        return m * count


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [(5, 7), (19, 40), (32516, 261701)]
    answers = [Solution2().rangeBitwiseAnd(m, n) for m, n in arguments]
    test(Solution().rangeBitwiseAnd, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
class Solution3(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        self.rec(root, None)
        return root
        
    def rec(self, root, prev):
        if not root:
            return prev
        prev = self.rec(root.right, prev)
        prev = self.rec(root.left, prev)
        root.right = prev
        root.left = None
        prev = root
        return prev

if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums = [1,2,5,3,4,None,6]
    #nums = [1, 2]
    arguments = [BinaryTree(nums).root]
    answers = [sorted([x for x in nums if x != None])]
    test(Solution3().flatten, arguments, answers, mode='inorder')
    
    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        """
        if not nums:
            return False

        def rec(i, j, target):
            while j > i:
                mid = (i + j) / 2
                if target == nums[mid]:
                    return True
                elif i + 1 == j:
                    return False
                elif mid + 1 == j or nums[i] <= target <= nums[mid - 1]:
                    return rec(i, mid, target)
                elif nums[mid + 1] <= target <= nums[j - 1]:
                    return rec(mid + 1, j, target)
                else:
                    return rec(i, mid, target) or rec(mid + 1, j, target)

        return rec(0, len(nums), target)


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [([1, 1, 1, 3, 1], 3)]
    answers = [True]
    test(Solution().search, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s or s[0] == '0':
            return 0

        ans = [1, 1]
        for i in xrange(1, len(s)):
            if not ans[-1] and not ans[-2]:
                return 0
            ans1 = ans[-1] if s[i] in '123456789' else 0
            ans2 = ans[-2] if 10 <= int(s[i - 1:i + 1]) <= 26 else 0
            ans.append(ans1 + ans2)
        return ans[-1]


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = ["12", "103", "1030"]
    answers = [2, 1, 0]
    test(Solution().numDecodings, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        positive = (dividend < 0) is (divisor < 0)
        dividend, divisor = abs(dividend), abs(divisor)
        res = 0
        while dividend >= divisor:
            temp, i = divisor, 1
            while dividend >= temp:
                dividend -= temp
                res += i
                i <<= 1
                temp <<= 1
        if not positive:
            res = -res
        return min(max(-2147483648, res), 2147483647)


if __name__ == "__main__":
    from leetcodelib import test
    from random import randint
    INT_MIN, INT_MAX = -2147483648, 2147483647
    arguments = [(INT_MIN, -1)] + [(randint(
        INT_MIN, INT_MAX), randint(INT_MIN, INT_MAX)) for _ in xrange(100)]
    answers = [INT_MAX
               ] + [int(float(x[0]) / float(x[1])) for x in arguments[1:]]
    test(Solution2().divide, arguments, answers)
    test(Solution3().divide, arguments, answers)
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        mp = {')': '(', ']': '[', '}': '{'}
        stack = []
        for c in s:
            if c in mp.values():
                stack.append(c)
            elif not stack or mp[c] != stack.pop():
                return False
        return False if stack else True


if __name__ == "__main__":
    from leetcodelib import test
    arguments = ['()', '))()', '(())', '[){}', '{(})', '{[]}', '()(']
    answers = [True, False, True, False, False, True, False]
    test(Solution().isValid, arguments, answers)
Exemple #12
0
        if not head or not head.next or not head.next.next:
            return head

        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next

        prev, curr = None, slow.next
        slow.next = None
        while curr:
            curr.next, prev, curr = prev, curr, curr.next

        node, next_node = head, prev
        while node:
            print node, next_node
            node.next, node, next_node = next_node, next_node, node.next
        return head


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums = [range(x) for x in xrange(1, 6)]
    arguments = [LinkedList(x).head for x in nums]
    answers = [[0], [0, 1], [0, 2, 1], [0, 3, 1, 2], [0, 4, 1, 3, 2]]
    test(Solution().reorderList, arguments, answers, inds=[3])

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #13
0
        if status[i] and isinstance(status[i][0], int):
            tmp = []
            for x in status[i]:
                word = wordDict[x]
                j = i - len(word)
                if j != 0:
                    tmp.extend([
                        s + " " + word
                        for s in self.translate(j, status, wordDict)
                    ])
                else:
                    tmp.append(word)
            status[i] = tmp
        return status[i]


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [("catsanddog", ["cat", "cats", "and", "sand", "dog"])]
    answers = [["cats and dog", "cat sand dog"]]

    #arguments = [("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    #              ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"])]
    #answers = ['a']

    test(Solution().wordBreak, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        if len(nums) < 2:
            return nums

        i = len(nums) - 1
        while i > 0 and nums[i] <= nums[i - 1]:
            i -= 1

        if i > 0:
            j = i
            while j < len(nums) and nums[j] > nums[i - 1]:
                j += 1
            nums[i - 1], nums[j - 1] = nums[j - 1], nums[i - 1]

        j = len(nums) - 1
        while i < j:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1
            j -= 1
        return nums


if __name__ == "__main__":
    from leetcodelib import test
    arguments = [[1, 2, 3], [3, 2, 1], [1, 1, 5], [3, 7, 4, 3, 5, 4, 2, 1]]
    answers = [[1, 3, 2], [1, 2, 3], [1, 5, 1], [3, 7, 4, 4, 1, 2, 3, 5]]

    test(Solution().nextPermutation, arguments, answers)
        numerator, denominator = abs(numerator), abs(denominator)

        int_part, x = divmod(numerator, denominator)
        if not x:
            return symbol + str(int_part)

        nums, ref, i = [int_part, "."], {}, 2
        while x and x not in ref:
            ref[x] = i
            n, x = divmod(x * 10, denominator)
            nums.append(n)
            i += 1

        if not x:
            return symbol + "".join([str(x) for x in nums])
        else:
            j = ref[x]
            return symbol + "".join([str(x) for x in nums[:j]]) + "(" + \
                "".join([str(x) for x in nums[j:]]) + ")"


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [(1, 2), (2, 1), (2, 3), (1, 90), (-50, 8), (0, -5)]
    answers = ["0.5", "2", "0.(6)", "0.0(1)", "-6.25", "0"]
    test(Solution().fractionToDecimal, arguments, answers, inds=None)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #16
0
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(candidates, target, index, path, ans):
            if target < 0:
                return

            if target == 0:
                ans.append(path)
                return

            for i in xrange(index, len(candidates)):
                dfs(candidates, target - candidates[i], i,
                    path + [candidates[i]], ans)

        candidates.sort()
        ans = []
        dfs(candidates, target, 0, [], ans)
        return ans


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [([2, 3, 6, 7], 7)]
    answers = [[[7], [2, 2, 3]]]
    test(Solution2().combinationSum, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
            pnext = right.next
            prev.next, right.next, left.next = right, left, right.next
            prev, left = left, pnext
            right = left.next if left else None
        #return dummy.next
        return LinkedList(dummy.next).values()


class Solution2(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(None)
        dummy.next = head
        prev = dummy
        while prev.next and prev.next.next:
            first, second = prev.next, prev.next.next
            prev.next, second.next, first.next = second, first, second.next
            prev = first
        return dummy.next


if __name__ == "__main__":
    from leetcodelib import test
    num_lists = [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
    arguments = [LinkedList(nums).head for nums in num_lists]
    answers = [None, [0], [1, 0], [1, 0, 2], [1, 0, 3, 2]]
    test(Solution2().swapPairs, arguments, answers)
Exemple #18
0
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums:
            return []
        n1, n2, c1, c2 = None, None, 0, 0
        for n in nums:
            if n == n1:
                c1 += 1
            elif n == n2:
                c2 += 1
            elif c1 == 0:
                n1, c1 = n, 1
            elif c2 == 0:
                n2, c2 = n, 1
            else:
                c1 -= 1
                c2 -= 1
        return [x for x in [n1, n2] if nums.count(x) > len(nums) / 3]


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [[1, 2]]
    answers = [[1, 2]]
    test(Solution2().majorityElement, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        prev, node = None, head
        while node:
            next_node = node.next
            node.next = prev
            prev, node = node, next_node
        return prev
    
class Solution2(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        if not head.next:
            return head
        new_head = self.reverseList(head.next)
        head.next.next, head.next = head, None
        return new_head

if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [LinkedList([1, 2]).head]
    answers = [[2, 1]]
    test(Solution2().reverseList, arguments, answers)
    
    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #20
0
                    stack.append(x.label)
                center.neighbors.append(ref[x.label][1])
        return ref[label][1]


class Solution2:
    # @param node, a undirected graph node
    # @return a undirected graph node
    def cloneGraph(self, node):
        if not node:
            return
        return self.copy(node, {})

    def copy(self, node, ref):
        label = node.label
        if label not in ref:
            ref[label] = UndirectedGraphNode(node.label)
            ref[label].neighbors = [self.copy(x, ref) for x in node.neighbors]
        return ref[label]


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = []
    answers = []
    test(Solution().cloneGraph, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #21
0
            tmp = []
            for m, i in masks:
                for x in range(i + 1, n):
                    newm = list(m)
                    newm[x] = True
                    tmp.append((newm, x))
            masks = tmp

        masks, _ = zip(*masks)
        comb_list = []
        if flip:
            for m in masks:
                comb_list.append([i + 1 for i, x in enumerate(m) if not x])
        else:
            for m in masks:
                comb_list.append([i + 1 for i, x in enumerate(m) if x])
        return comb_list


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [(4, 2), (4, 3)]
    answers = [[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]],
               [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]]

    test(Solution().combine, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #22
0
class Solution2(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.rec(root)

    def rec(self, root, minval=-float('inf'), maxval=float('inf')):
        if not root:
            return True
        if root.val <= minval or root.val >= maxval:
            return False
        return self.rec(root.left, minval, root.val) and self.rec(
            root.right, root.val, maxval)


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums = [[4, 2, 6, 1, 3, 5, 7], [4, 2, 5, 3, 1, 6, 7],
            [4, 2, 5, 1, 3, 7, 6], [10, 5, 15, None, None, 6, 20]]

    arguments = [BinaryTree(num).root for num in nums]
    answers = [True, False, False, False]
    test(Solution2().isValidBST, arguments, answers, inds=None)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #23
0
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        if not root or k == 0:
            return None
        node, stack = root, []
        while node or stack:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack.pop()
                k -= 1
                if k == 0:
                    return node.val
                node = node.right


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums = [[1, None, 2], [3, 1, 4, None, 2]]
    ks = [2, 2]
    arguments = [(BinaryTree(nums[i]).root, ks[i]) for i in xrange(len(ks))]
    answers = [2, 2]
    test(Solution().kthSmallest, arguments, answers, inds=[1])

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #24
0
        return max(maxlen, len(s) - i)


class Solution2(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s) <= 1:
            return len(s)
        overall, i, ref = 1, 0, {s[0]: 0}
        for j in xrange(1, len(s)):
            if s[j] in ref and ref[s[j]] >= i:
                i = ref[s[j]] + 1
            ref[s[j]] = j
            overall = max(overall, j - i + 1)
        return overall


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [("abcabcbb", ), ("bbbbb", ), ("pwwkew", ), ("au", ),
                 ("dvdf", )]
    answers = [3, 1, 3, 2, 3]
    test(Solution2().lengthOfLongestSubstring, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
                matrix[i][j], matrix[i][~j] = matrix[i][~j], matrix[i][j]

        return matrix


class Solution2(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix[0])
        matrix = matrix[::-1]

        for i in xrange(n - 1):
            for j in xrange(i + 1, n):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

        return matrix


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [[[1, 2], [3, 4]]]
    answers = [[[3, 1], [4, 2]]]
    test(Solution2().rotate, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        :rtype: List[List[int]]
        """
        if not root:
            return []

        level, ans, direction = [root], [], -1
        while level:
            tmp, values = [], []
            for i in xrange(len(level)):
                values.append(level[i].val)
                children = [level[~i].left, level[~i].right]
                for child in children[::direction]:
                    if child:
                        tmp.append(child)
            ans.append(values)
            level = tmp
            direction = -direction
        return ans


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums = [[3, 9, 20, None, None, 15, 7], [1, 2, 3, 4, None, None, 5]]
    arguments = [BinaryTree(x).root for x in nums]
    answers = [[[3], [20, 9], [15, 7]], [[1], [3, 2], [4, 5]]]
    test(Solution().zigzagLevelOrder, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #27
0
        """
        if len(s) < 2:
            return 0

        maxlen = 0
        heads = [None]
        for i in xrange(1, len(s)):
            if s[i] == '(':
                head = None
            else:
                j = i - 1 if not heads[i - 1] else heads[i - 1] - 1
                if s[j] == ')':
                    head = None
                elif j == 0 or heads[j - 1] == None:
                    head = j
                else:
                    head = heads[j - 1]
            if head != None:
                maxlen = max(maxlen, i - head + 1)
            heads.append(head)
        return maxlen


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = ["()()"]
    answers = [4]
    test(Solution2().longestValidParentheses, arguments, answers)

    testfile = __file__.replace('.py', '.yaml')
    run_testfile(testfile, Solution2().longestValidParentheses)
            tmp, board[i][j] = board[i][j], "#"
            status = walk(i - 1, j, ind + 1) or walk(
                i + 1, j, ind + 1) or walk(i, j - 1, ind + 1) or walk(
                    i, j + 1, ind + 1)
            board[i][j] = tmp
            return status

        for i in xrange(len(board)):
            for j in xrange(len(board[0])):
                if walk(i, j, 0):
                    return True
        return False


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    b1 = ["ABCE", "SFCS", "ADEE"]
    b2 = ["aa"]
    b3 = ["ABCE", "SFES", "ADEE"]
    b4 = ["aaa", "abb", "abb", "bbb", "bbb", "aaa", "bbb", "abb", "aab", "aba"]

    arguments = [(b1, "ABCCED"), (b1, "SEE"), (b1, "ABCB"), (b2, "aaa"),
                 (b3, "ABCESEEEFS"), (b4, "aabaaaabbb")]
    answers = [True, True, False, False, True, False]
    test(Solution().exist, arguments, answers, inds=1)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        """
        ans = []
        node, stack, tot, path = root, [], 0, []
        while node or stack:
            if node:
                tot += node.val
                path.append(node.val)
                if not node.left and not node.right:
                    if tot == sum:
                        ans.append(path)
                    node = None
                else:
                    if node.right:
                        stack.append((tot, node.right, list(path)))
                    node = node.left
            else:
                tot, node, path = stack.pop()
        return ans


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1]
    arguments = [(BinaryTree(nums).root, 22)]
    answers = [[[5, 4, 11, 2], [5, 8, 4, 5]]]
    test(Solution2().pathSum, arguments, answers, mode='1D')

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Exemple #30
0
                print i, h, t, nums[i], nums[h], nums[t]
                while h < t:
                    if nums[h] + nums[t] < -nums[i]:
                        h += 1
                    elif nums[h] + nums[t] > -nums[i]:
                        t -= 1
                    else:
                        res.append([nums[i], nums[h], nums[t]])
                        h, t = h + 1, t - 1
                        print res, h, t, nums[h], nums[t]
                        while h < t and nums[h] == nums[h - 1]:
                            h += 1
                        while h < t and nums[t] == nums[t + 1]:
                            t -= 1
        return res


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [[-1, 0, 1, 2, -1, -4], [0, 0, 0, 0], [1, -1, -1, 0],
                 [-4, -2, 1, -5, -4, -4, 4, -2, 0, 4, 0, -2, 3, 1, -5, 0],
                 [-2, 0, 1, 1, 2]]
    answers = [[[-1, 0, 1], [-1, -1, 2]], [[0, 0, 0]], [[-1, 0, 1]],
               [[-5, 1, 4], [-4, 0, 4], [-4, 1, 3], [-2, -2, 4], [-2, 1, 1],
                [0, 0, 0]], [[-2, 0, 2], [-2, 1, 1]]]
    test(Solution2().threeSum, arguments, answers, inds=[-1], mode='1D')

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)