LeetCode生成测试用例
以下版本均为go语言版本,可能或者有C++版本
字符串生成二叉树
参考链接:https://blog.csdn.net/u012140251/article/details/110010850
func generateTree(str string) (root *TreeNode) {
s := strings.TrimLeft(str, "[")
s = strings.TrimRight(s, "]")
arr := strings.Split(s, ",")
if len(arr) == 0 || arr[0] == "null" {
return
}
root = new(TreeNode)
root.Val, _ = strconv.Atoi(arr[0])
arr = arr[1:]
queue := []*TreeNode{root}
for len(queue) > 0 && len(arr) > 0 {
node := queue[0]
queue = queue[1:]
if arr[0] != "null" {
node.Left = new(TreeNode)
node.Left.Val, _ = strconv.Atoi(arr[0])
queue = append(queue, node.Left)
}
arr = arr[1:]
if len(arr) > 0 {
if arr[0] != "null" {
node.Right = new(TreeNode)
node.Right.Val, _ = strconv.Atoi(arr[0])
queue = append(queue, node.Right)
}
arr = arr[1:]
}
}
return
}
字符串生成数组
字符串生成一维数组
func generateArr(str string) []int {
s := strings.TrimLeft(str, "[")
s = strings.TrimRight(s, "]")
strArr := strings.Split(s, ",")
res := make([]int, len(strArr))
for index, val := range strArr {
res[index], _ = strconv.Atoi(val)
}
return res
}
func main() {
arr := generateArr("[1,2,3,4,5]")
fmt.Printf("%v", arr)
}
字符串生成二维数组
func generateArr2(str string) [][]int {
s := strings.TrimLeft(str, "[")
s = strings.TrimRight(s, "]")
strArr := strings.Split(s, "],")
res := make([][]int, 0)
for _, str := range strArr {
strAr := strings.TrimLeft(str, "[")
strA := strings.Split(strAr, ",")
tmp := make([]int, len(strA))
for index, val := range strA {
tmp[index], _ = strconv.Atoi(val)
}
res = append(res, tmp)
}
return res
}
func main() {
arr := generateArr2("[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]")
fmt.Printf("%v", arr)
}





