LC 2788. 按分隔符拆分字符串

2788. 按分隔符拆分字符串

难度 简单

题目大意:

给你一个字符串数组 words 和一个字符 separator ,请你按 separator 拆分 words 中的每个字符串。

返回一个由拆分后的新字符串组成的字符串数组,不包括空字符串

注意

  • separator 用于决定拆分发生的位置,但它不包含在结果字符串中。
  • 拆分可能形成两个以上的字符串。
  • 结果字符串必须保持初始相同的先后顺序。

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • words[i] 中的字符要么是小写英文字母,要么就是字符串 ".,|$#@" 中的字符(不包括引号)
  • 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"] 。

分析

我们只需要words中每一个字符串进行拆解即可,最后一个点需要特判一下

枚举

class Solution {
public:
    vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
        vector<string> res;
        for (int i = 0; i < words.size(); i ++) {
            for (int j = 0, k = 0; j < words[i].size(); j ++) {
                if (words[i][j] == separator || j == words[i].size() - 1) {
                    if (j == words[i].size() - 1 && words[i][j] != separator)
                        res.push_back(words[i].substr(k, j - k + 1));
                    else if (j - k >= 1) { 
                        res.push_back(words[i].substr(k, j - k));
                    }
                    k = j + 1;
                }
            }
        }
        return res;
    }
};

结束了

你可能感兴趣的:(leetcode,算法,c++,学习记录)