【LetMeFly】2788.按分隔符拆分字符串:模擬(字符串處理)
力扣題目鏈接:https://leetcode.cn/problems/split-strings-by-separator/
給你一個字符串數(shù)組 words
和一個字符 separator
,請你按 separator
拆分 words
中的每個字符串。
返回一個由拆分后的新字符串組成的字符串數(shù)組,不包括空字符串 。
注意
-
separator
用于決定拆分發(fā)生的位置,但它不包含在結果字符串中。 - 拆分可能形成兩個以上的字符串。
- 結果字符串必須保持初始相同的先后順序。
?
示例 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" 因此,結果數(shù)組為 ["one","two","three","four","five","six"] 。
示例 2:
輸入:words = ["$easy$","$problem$"], separator = "$" 輸出:["easy","problem"] 解釋:在本示例中,我們進行下述拆分: "$easy$" 拆分為 "easy"(不包括空字符串) "$problem$" 拆分為 "problem"(不包括空字符串) 因此,結果數(shù)組為 ["easy","problem"] 。
示例 3:
輸入:words = ["|||"], separator = "|" 輸出:[] 解釋:在本示例中,"|||" 的拆分結果將只包含一些空字符串,所以我們返回一個空數(shù)組 [] 。
?
提示:
1 <= words.length <= 100
1 <= words[i].length <= 20
-
words[i]
中的字符要么是小寫英文字母,要么就是字符串".,|$#@"
中的字符(不包括引號) -
separator
是字符串".,|$#@"
中的某個字符(不包括引號)
方法一:模擬
新建一個空的字符串數(shù)組作為答案,遍歷字符串數(shù)組的所有字符串,使用一個變量last
記錄上一個separator
的位置(初始值為-1
)。
接著遍歷這個字符串的每一個字符,如果遍歷到了字符串尾或當前字符為separator
,就看當前下標和last
之間是否有字符存在。若有,則添加到答案數(shù)組中。
最終返回答案數(shù)組即為答案。文章來源:http://www.zghlxwxcb.cn/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(sumc?haracter(words)),時間復雜度為字符串數(shù)組中字符串的個數(shù)
- 空間復雜度 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
同步發(fā)文于CSDN,原創(chuàng)不易,轉載經(jīng)作者同意后請附上原文鏈接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/135724019文章來源地址http://www.zghlxwxcb.cn/news/detail-811251.html
到了這里,關于LeetCode 2788.按分隔符拆分字符串:模擬(字符串處理)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!