|
发表于 2021-4-12 18:47:56
|
显示全部楼层
Python 版(带注释):
- data=["# a", "## b", "## c", "### d", "### e", "### f", "## g", "### h", "# i", "## j", "## k", "### l", "#### m",
- "#### n", "### o", "# p", "## q", "### r", "### s", "## t", "### u", "# v", "## w", "### x", "### y", "## z"]
- def func(lst):
- res = [] # 用于存放结果
- cnt = [0 for i in range(len(lst) + 1)] # 用于存放前缀层级
- for i in range(len(lst)):
- n = lst[i].count('#') # 统计前缀数量
- cnt[n - 1] += 1 # 对应位置加一
- cnt[n:] = [0] * (len(lst) - n) # 对应位置后面的都清零, 因为层级是连续的,也就是说,
- # a, ## b, ### c ## d ### e 这个 e 是属于 d 的, 所以结果应是 1.2.1, 而不是 1.2.2
- # res.append(['.'.join(map(str, cnt[:n])), lst[i].replace('#', '').strip()])
- # 这种方法保险,但貌似并没什么用, 还不如下面那种
- res.append(['.'.join(map(str, cnt[:n])), lst[i][-1]]) # 把层级拼接起来,并放入标题名称
- return res
- print(func(data))
复制代码
Golang 版:
由于思路和 Python 版 一样, 这里就不写注释了
- package main
- import (
- "fmt"
- "strings"
- "strconv"
- )
- func to_string(a []int) []string {
- res := make([]string, len(a))
- for i := 0; i < len(a); i++ {
- res[i] = strconv.Itoa(a[i])
- }
- return res
- }
- func fn(a []string) ([][]string) {
- res := [][]string{}
- tmp := []string{}
- var cnt []int = make([]int, len(a) + 1)
- // 初始化 cnt, 用于统计层级
- for i := 0; i <= len(a); i++ {
- cnt[i] = 0
- }
- for i := 0; i < len(a); i++ {
- n := strings.Count(a[i], "#")
- cnt[n - 1] += 1
- for j := n; j < len(a); j++ {
- cnt[j] = 0
- }
- tmp = to_string(cnt)
- res = append(res, []string{strings.Join(tmp[:n], "."), strings.TrimSpace(strings.Replace(a[i], "#", "", -1))})
- }
- return res
- }
- func main() {
- res := fn([]string{"# a", "## b", "## c", "### d", "### e", "### f", "## g", "### h", "# i", "## j", "## k", "### l", "#### m",
- "#### n", "### o", "# p", "## q", "### r", "### s", "## t", "### u", "# v", "## w", "### x", "### y", "## z"})
- fmt.Println(res)
- }
复制代码 |
评分
-
查看全部评分
|