一、题目
1、题目描述
给你一个字符串数组
words
和一个字符separator
,请你按separator
拆分words
中的每个字符串。返回一个由拆分后的新字符串组成的字符串数组,不包括空字符串 。
注意
separator
用于决定拆分发生的位置,但它不包含在结果字符串中。- 拆分可能形成两个以上的字符串。
- 结果字符串必须保持初始相同的先后顺序。
2、接口描述
class Solution {
public:vector<string> splitWordsBySeparator(vector<string>& words, char separator) {}
};
3、原题链接
2788. 按分隔符拆分字符串
二、解题报告
1、思路分析
直接遍历所有字符串,按照分隔符保存子串即可
2、复杂度
时间复杂度: O(nm) 空间复杂度:O(m),n为字符串个数,m为最长字符串长度
3、代码详解
C++
class Solution {
public:vector<string> splitWordsBySeparator(vector<string>& words, char separator) {vector<string> ret;for(auto& s : words){string str;for(auto x : s)if(x != separator)str.push_back(x);else if(str.size())ret.emplace_back(str) , str.clear();if(str.size()) ret.emplace_back(str);}return ret;}
};
Python3
class Solution:def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:ret = []for word in words:ret += [x for x in word.split(separator) if len(x)]return ret