【LeetCode】每日一题 2024_1_20 按分隔符拆分字符串(模拟/库函数)

文章目录

随便聊聊时间


LeetCode?启动!!!

时隔半个月,LeetCode 每日一题重新开张,寒假学习,正式开始

题目:按分隔符拆分字符串

题目链接:2788. 按分隔符拆分字符串

题目描述

代码与解题思路

可以直接手动模拟:

go 复制代码
func splitWordsBySeparator(words []string, separator byte) (ans []string) {
    for i := 0; i < len(words); i++ {
        s := ""
        for j := 0; j < len(words[i]); j++ {
            if words[i][j] == separator {
                if s != "" {
                    ans = append(ans, s)
                    s = ""
                }
                continue
            }
            s += string(words[i][j])
        }
        if s != "" {
            ans = append(ans, s)
        }
    }
    return ans
}

也可以直接调库:

go 复制代码
func splitWordsBySeparator(words []string, separator byte) (ans []string) {
    for _, str := range words {
        // string([]byte{separator})
        s := strings.Split(str, string(separator))
        for _, v := range s {
            if len(v) > 0 {
                ans = append(ans, v)
            }
        }
    }
    return ans
}

看官方题解学到新知识:

我原先使用的:string(separator),可以将 byte 类型的一个字符转换成 string 类型,官方的那个更高级一点,他用的:string([ ]byte{separator}),如果分隔符不止一个字符的话,我们可以给这个 byte 切片手动追加字符

相关推荐
Raink老师5 小时前
【AI面试临阵磨枪-62】设计基于 RAG 的内部知识库问答平台(多租户、权限、文件上传、实时更新)
人工智能·面试·职场和发展
smj2302_796826526 小时前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
炽烈小老头7 小时前
【每天学习一点算法 2026/05/25】矩阵中的最长递增路径
学习·算法·矩阵
我爱cope7 小时前
【Agent智能体6 | 智能体AI评估】
人工智能·职场和发展
叁散7 小时前
实验报告:5G 仿真环境与基本链路模拟
算法
从负无穷开始的三次元代码生活8 小时前
算法零碎灵感点分享
算法
染指11108 小时前
9.LangChain框架(实现RAG)
数据库·人工智能·算法·机器学习·ai·大模型
我爱cope8 小时前
【Agent智能体5 | 任务分解:识别工作流中的步骤】
人工智能·职场和发展
大数据三康8 小时前
在spyder进行的遗传算法练习
开发语言·python·算法
Gene_20228 小时前
轮式底盘的微分平坦
算法