【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 切片手动追加字符

相关推荐
晴天的雨.99219 分钟前
[C++算法]快乐数
数据结构·c++·算法
孤狼warrior23 分钟前
SCTR 五次失败的安全 BN 路由器
人工智能·python·深度学习·算法·安全·yolo
影视飓风TIM25 分钟前
C++11 核心新特性完整梳理
数据结构·c++·算法
晴天的雨.99226 分钟前
[C++]算法双指针 复写0
数据结构·c++·算法
橘子汽水16841 分钟前
Leetcode 128,49最长连续序列,字母异位词分组
java·算法·leetcode
圣保罗的大教堂43 分钟前
leetcode 1140. 石子游戏 II 中等
leetcode
mmmmath_343 分钟前
LeetCode.438.找到字符串中所有字母异位词
数据结构·算法·leetcode
Nil2081 小时前
leetcode 22括号生成
算法·leetcode·深度优先
Navigator_Z1 小时前
LeetCode //C - 1237. Find Positive Integer Solution for a Given Equation
c语言·算法·leetcode