Algorithmic questions related to "public"

One, binary tree class

1. The nearest common ancestor of the binary tree

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        if not root or root == p or root ==q:
            return root
        left = self.lowestCommonAncestor(root.left,p,q)
        right = self.lowestCommonAncestor(root.right,p,q)
        if not left:
            return right
        if not right:
            return left
        return root

2. The nearest common ancestor of the binary search tree

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root or root==p or root==q:
            return root
        if root.val>p.val and root.val > q.val:
            return self.lowestCommonAncestor(root.left,p,q)
        if root.val<p.val and root.val < q.val:
            return self.lowestCommonAncestor(root.right,p,q)
        return root

3. The first common ancestor

Temporarily empty

Second, the linked list

1. The first common node of the two linked lists

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        # if not headA and not headB:
        #     return None
        node1,node2 = headA,headB 
        while node1 != node2:
            node1 = node1.next if node1 else headB
            node2 = node2.next if node2 else headA
        return node1

2. Circular linked list

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next :
            return False 

        slow = head
        fast = head
        while (fast and fast.next):
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True 
            
        return False

3. Circular linked list II

Temporarily empty

Three, dynamic programming

1. The longest common substring

The transfer equation is:preview

Simultaneous output length and common substring

class LCS3:
    def lcs3_dp(self, text1, text2):
        # input_y as column, input_x as row
        dp = [([0] * (len(text2)+1)) for i in range(len(text1)+1)]
        maxlen = maxindex = 0
        for i in range(1, len(text1)+1):
            for j in range(1, len(text2)+1):
                if i == 0 or j == 0:  # 在边界上,自行+1
                        dp[i][j] = 0
                if text1[i-1] == text2[j-1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                    if dp[i][j] > maxlen:  # 随时更新最长长度和长度开始的位置
                        maxlen = dp[i][j]
                        maxindex = i - maxlen

                else:
                    dp[i][j] = 0
        for dp_line in dp:
            print(dp_line)
        return maxlen, text1[maxindex:maxindex + maxlen]

2. The longest common subsequence:

The transfer equation is:

Output length and common subsequence at the same time:

class Solution:
    def LCS(list_n, list_m):
        # 计算LCS的长度
        n = len(list_n)
        m = len(list_m)
        dp = [[0]*(m+1) for _ in range(n+1)]
        for i in range(1, n+1):
            for j in range(1, m+1):
                if list_n[i-1] == list_m[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        print(dp[m][n])
        # 输出LCS
        if dp[-1][-1] == 0:
            return -1
        list_LCS = []
        i, j = n, m
        while i > 0 and j > 0:
            if list_n[i-1] == list_m[j-1]:
                list_LCS.append(list_n[i-1])
                i -= 1
                j -= 1
                continue
            else:
                if dp[i][j-1] >= dp[i-1][j]:
                    j -= 1
                else:
                    i -= 1
        return ''.join(list(reversed(list_LCS)))

Four, string class

Longest common prefix

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        res = ''
        max_str = max(strs)
        min_str = min(strs)
        for i,j in zip(max_str,min_str):
            if i==j:
                res+=i
            else:
                return res
        return min_str

Guess you like

Origin blog.csdn.net/Matrix_cc/article/details/108632888