当前位置:   article > 正文

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

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

题目来源

力扣每日一题;题序:2788

我的题解

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

直接调用相关API

时间复杂度:O(n)。没有考虑API内部时间
空间复杂度:O(1)。没考虑API内部细节

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
方法二 模拟

模拟分割

时间复杂度:O(nm)。n是中的字符串数,m是最长字符串的长度
空间复杂度:O(m)。在分割函数中存储结果的list大小

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/45288
推荐阅读
相关标签