【LetMeFly】2788.按分隔符拆分字符串:模拟(字符串处理)
力扣题目链接:https://leetcode.cn/problems/split-strings-by-separator/
给你一个字符串数组 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 = "|" 输出:[] 解释:在本示例中,"|||" 的拆分结果将只包含一些空字符串,所以我们返回一个空数组 [] 。
提示:
1 <= words.length <= 100
1 <= words[i].length <= 20
-
words[i]
中的字符要么是小写英文字母,要么就是字符串".,|$#@"
中的字符(不包括引号) -
separator
是字符串".,|$#@"
中的某个字符(不包括引号)
方法一:模拟
新建一个空的字符串数组作为答案,遍历字符串数组的所有字符串,使用一个变量last
记录上一个separator
的位置(初始值为-1
)。
接着遍历这个字符串的每一个字符,如果遍历到了字符串尾或当前字符为separator
,就看当前下标和last
之间是否有字符存在。若有,则添加到答案数组中。
最终返回答案数组即为答案。文章来源:https://www.toymoban.com/news/detail-811251.html
- 时间复杂度 O ( s u m c h a r a c t e r ( w o r d s ) ) O(sum_character(words)) O(sumcharacter(words)),时间复杂度为字符串数组中字符串的个数
- 空间复杂度 O ( 1 ) O(1) O(1),力扣的算法返回值不计入算法的空间复杂的
AC代码
C++
class Solution {
public:
vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
vector<string> ans;
for (string& word : words) {
int last = -1;
for (int i = 0; i <= word.size(); i++) {
if (i == word.size() || word[i] == separator) {
if (i - last > 1) {
ans.push_back(word.substr(last + 1, i - last - 1));
}
last = i;
}
}
}
return ans;
}
};
Python
# from typing import List
class Solution:
def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
ans = []
for word in words:
splited = word.split(separator)
for this in splited: # 过滤空串
if this:
ans.append(this)
return ans
同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/135724019文章来源地址https://www.toymoban.com/news/detail-811251.html
到了这里,关于LeetCode 2788.按分隔符拆分字符串:模拟(字符串处理)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!