D11Q1

题目来源leetcode每日一题2024.1.17

2788. 按分隔符拆分字符串

题目

提示

给你一个字符串数组 words 和一个字符 separator ,请你按 separator 拆分 words 中的每个字符串。

返回一个由拆分后的新字符串组成的字符串数组,不包括空字符串 。

注意

  • separator 用于决定拆分发生的位置,但它不包含在结果字符串中。
  • 拆分可能形成两个以上的字符串。
  • 结果字符串必须保持初始相同的先后顺序。

示例 1:

输入:words = ["one.two.three","four.five","six"], separator = "."
输出:["one","two","three","four","five","six"]
解释:在本示例中,我们进行下述拆分:

"one.two.three" 拆分为 "one", "two", "three"
"four.five" 拆分为 "four", "five"
"six" 拆分为 "six" 

因此,结果数组为 ["one","two","three","four","five","six"] 。

示例 2:

输入:words = ["$easy$","$problem$"], separator = "$"
输出:["easy","problem"]
解释:在本示例中,我们进行下述拆分:

"$easy$" 拆分为 "easy"(不包括空字符串)
"$problem$" 拆分为 "problem"(不包括空字符串)

因此,结果数组为 ["easy","problem"] 。

示例 3:

输入:words = ["|||"], separator = "|"
输出:[]
解释:在本示例中,"|||" 的拆分结果将只包含一些空字符串,所以我们返回一个空数组 [] 。 

思路:按序遍历words,判断words[i]是否为separator,若不是就加入数组s,若是则将s用join函数整合放入ans数组中,最后输出ans。

代码:

#自用代码,不是leetcode提交代码
words = ["|||"]
separator = "|"
ans=[]
s=[]
for i in words:
    for j in i:
        if j !=separator:
            s.append(j)
        else:
            put=''.join(s)
            if put!='':#判断s是否为空,防止防入空字符串
                ans.append(put)
                s=[]
    put = ''.join(s)#遍历下一个words前将s放入ans
    if put != '':
        ans.append(put)
        s = []
print(ans)

思路2

直接使用split()方法拆分数组,注意不能直接拆分words,要拆分words[i],而且拆分后的数组中有空字符串,需要去掉字符串,最后整合所有拆分数组即可。

代码2:

class Solution:
    def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
        res = list()
        for w in words:
            res += w.split(separator)
        return [i for i in res if i != ""]

知识点

1.join()可以整合数组

2. .split()可以按分割符拆分数组

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值