2024.1.20力扣每日一题——按分隔符拆分字符串

2024.1.20

      • 题目来源
      • 我的题解
        • [方法一 API工程师(String.split+Stream)](#方法一 API工程师(String.split+Stream))
        • [方法二 模拟](#方法二 模拟)

题目来源

力扣每日一题;题序:2788

我的题解

方法一 API工程师(String.split+Stream)

直接调用相关API
时间复杂度 :O(n)。没有考虑API内部时间
空间复杂度:O(1)。没考虑API内部细节

java 复制代码
public List<String> splitWordsBySeparator(List<String> words, char separator) {
      List<String> res=new ArrayList<>();
      for(String s :words){
          res.addAll(Arrays.stream(s.split("\\"+separator))
                          .filter(c->!c.isEmpty())
                          .collect(Collectors.toList()));
      }
      return res;
  }
方法二 模拟

模拟分割
时间复杂度:O(nm)。n是中的字符串数,m是最长字符串的长度

空间复杂度:O(m)。在分割函数中存储结果的list大小

java 复制代码
public List<String> splitWordsBySeparator(List<String> words, char separator) {
    List<String> res=new ArrayList<>();
    for(String s :words){
        res.addAll(split(s,separator));
    }
    return res;
}
public List<String> split(String s,char separator){
    int n=s.length();
    int left=0,right=0;
    List<String> res=new ArrayList<>();
    while(right<n){
        while(right<n&&s.charAt(right)!=separator){
            right++;
        }
        String t=s.substring(left,right);
        if(!t.isEmpty())
            res.add(t);
        left=right+1;
        right=left;
    }
    return res;
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

相关推荐
he___H20 分钟前
数据结构-移位
数据结构
电子_咸鱼1 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫1 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
rit84324991 小时前
基于MATLAB实现基于距离的离群点检测算法
人工智能·算法·matlab
my rainy days3 小时前
C++:友元
开发语言·c++·算法
haoly19893 小时前
数据结构和算法篇-归并排序的两个视角-迭代和递归
数据结构·算法·归并排序
微笑尅乐3 小时前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
小梁努力敲代码3 小时前
java数据结构--List的介绍
java·开发语言·数据结构
摸鱼的老谭3 小时前
构建Agent该选Python还是Java ?
java·python·agent
lang201509284 小时前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端