那些和“公共“有关的算法题

一、二叉树类

1、二叉树的最近公共祖先

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、二叉搜索树的最近公共祖先

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、首个共同祖先

暂时空

二、链表类

1、两个链表的第一个公共节点

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、环形链表

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、环形链表 II

暂时为空

三、动态规划类

1、最长公共子串

转移方程为:preview

同时输出长度和公共子串

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、最长公共子序列:

转移方程为:

同时输出长度和公共子序列:

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[n][m])
        # 输出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)))
class Solution:
    def LCS(self , s1 , s2 ):
        # write code here
        m,n=len(s1),len(s2)
        dp=[['']*(n+1) for _ in range(m+1)]
        for i in range(1,m+1):
            for j in range(1,n+1):
                if s1[i-1]==s2[j-1]:
                    dp[i][j]=dp[i-1][j-1]+s1[i-1]
                else:
                    ls1=dp[i][j-1]
                    ls2=dp[i-1][j]
                    if len(ls1)>len(ls2):
                        dp[i][j]=ls1
                    else:
                        dp[i][j]=ls2
        if dp[m][n]=='':
            return '-1'
        else:
            return dp[m][n]

 

四、字符串类

最长公共前缀

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值