mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Merge pull request #1595 from PanYuHaa/master
更新0129.求根到叶子结点数字之和中,增加0100.相同的树go语言的递归解法,增加0005.最长回文子串增加go语言的dp解法
This commit is contained in:
@ -363,6 +363,34 @@ class Solution:
|
|||||||
Go:
|
Go:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
func longestPalindrome(s string) string {
|
||||||
|
maxLen := 0
|
||||||
|
left := 0
|
||||||
|
length := 0
|
||||||
|
dp := make([][]bool, len(s))
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
dp[i] = make([]bool,len(s))
|
||||||
|
}
|
||||||
|
for i := len(s)-1; i >= 0; i-- {
|
||||||
|
for j := i; j < len(s); j++ {
|
||||||
|
if s[i] == s[j]{
|
||||||
|
if j-i <= 1{ // 情况一和情况二
|
||||||
|
length = j-i
|
||||||
|
dp[i][j]=true
|
||||||
|
}else if dp[i+1][j-1]{ // 情况三
|
||||||
|
length = j-i
|
||||||
|
dp[i][j] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if length > maxLen {
|
||||||
|
maxLen = length
|
||||||
|
left = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s[left: left+maxLen+1]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -237,6 +237,26 @@ class Solution:
|
|||||||
return True
|
return True
|
||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
> 递归法
|
||||||
|
```go
|
||||||
|
func isSameTree(p *TreeNode, q *TreeNode) bool {
|
||||||
|
if p != nil && q == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if p == nil && q != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if p == nil && q == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if p.Val != q.Val {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
Left := isSameTree(p.Left, q.Left)
|
||||||
|
Right := isSameTree(p.Right, q.Right)
|
||||||
|
return Left && Right
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
JavaScript:
|
JavaScript:
|
||||||
|
|
||||||
|
@ -250,20 +250,20 @@ Go:
|
|||||||
|
|
||||||
```go
|
```go
|
||||||
func sumNumbers(root *TreeNode) int {
|
func sumNumbers(root *TreeNode) int {
|
||||||
sum = 0
|
sum := 0
|
||||||
travel(root, root.Val)
|
dfs(root, root.Val, &sum)
|
||||||
return sum
|
return sum
|
||||||
}
|
}
|
||||||
|
|
||||||
func travel(root *TreeNode, tmpSum int) {
|
func dfs(root *TreeNode, tmpSum int, sum *int) {
|
||||||
if root.Left == nil && root.Right == nil {
|
if root.Left == nil && root.Right == nil {
|
||||||
sum += tmpSum
|
*sum += tmpSum
|
||||||
} else {
|
} else {
|
||||||
if root.Left != nil {
|
if root.Left != nil {
|
||||||
travel(root.Left, tmpSum*10+root.Left.Val)
|
dfs(root.Left, tmpSum*10 + root.Left.Val, sum)
|
||||||
}
|
}
|
||||||
if root.Right != nil {
|
if root.Right != nil {
|
||||||
travel(root.Right, tmpSum*10+root.Right.Val)
|
dfs(root.Right, tmpSum*10 + root.Right.Val, sum)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user