获得徽章 0
2023/8/15/16:20,镇江,大部多云,温度32摄氏度,空气质量:优,学习情况:啥也没学,来道力扣:给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
go代码:
func longestCommonSubsequence(a string, b string) int {
m, n := len(a), len(b)
dp := make([][]int, m+1)
for i := 0; i < m+1; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i < m+1; i++ {
for j := 0; j < n+1; j++ {
if i == 0 || j == 0 {
dp[i][j] = 0
continue
}
if a[i-1] == b[j-1] {
dp[i][j] = dp[i-1][j-1] + 1
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
}
}
}
return dp[m][n]
}
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
go代码:
func longestCommonSubsequence(a string, b string) int {
m, n := len(a), len(b)
dp := make([][]int, m+1)
for i := 0; i < m+1; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i < m+1; i++ {
for j := 0; j < n+1; j++ {
if i == 0 || j == 0 {
dp[i][j] = 0
continue
}
if a[i-1] == b[j-1] {
dp[i][j] = dp[i-1][j-1] + 1
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
}
}
}
return dp[m][n]
}
展开
3
点赞
#挑战每日一条沸点# 2023/8/12/13:23,镇江,大部多云,温度36摄氏度,空气质量:良,学习情况:啥也没学,来道力扣:给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
golang代码:
func isValidBST(root *TreeNode) bool {
var dfs func(*TreeNode, int, int) bool
dfs = func(n *TreeNode, up, low int) bool {
if n == nil {
return true
}
if n.Val <= low || n.Val >= up {
return false
}
return dfs(n.Left, n.Val, low) && dfs(n.Right, up, n.Val)
}
return dfs(root, math.MaxInt64, math.MinInt64)
}
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
golang代码:
func isValidBST(root *TreeNode) bool {
var dfs func(*TreeNode, int, int) bool
dfs = func(n *TreeNode, up, low int) bool {
if n == nil {
return true
}
if n.Val <= low || n.Val >= up {
return false
}
return dfs(n.Left, n.Val, low) && dfs(n.Right, up, n.Val)
}
return dfs(root, math.MaxInt64, math.MinInt64)
}
展开
评论
点赞
#挑战每日一条沸点# 2023/8/8/19:59,镇江,局部多云,温度29摄氏度,空气质量:优,学习情况:没学啥贴一道力扣吧:给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
go代码:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 {
return nil
}
l := 0
for inorder[l] != preorder[0]{
l++
}
root := &TreeNode{}
root.Val = preorder[0]
root.Left = buildTree(preorder[1:l+1], inorder[0:l])
root.Right = buildTree(preorder[l+1:], inorder[l+1:])
return root
}
go代码:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 {
return nil
}
l := 0
for inorder[l] != preorder[0]{
l++
}
root := &TreeNode{}
root.Val = preorder[0]
root.Left = buildTree(preorder[1:l+1], inorder[0:l])
root.Right = buildTree(preorder[l+1:], inorder[l+1:])
return root
}
展开
评论
点赞