【每日一题】按分隔符拆分字符串

Tag

【遍历】【getline】【字符串】【2024-01-20】


题目来源

2788. 按分隔符拆分字符串


解题思路

方法一:遍历

思路

分隔符在字符串开始和结束位置时不需要处理。

分隔符出现在字符串中间时,记录上一个分隔符到当前分隔符之间的字符串或者到字符串结尾的字符串,非空即可加入到答案数组中。

算法

class Solution {
public:
    vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
        vector<string> res;
        for (auto& word : words) {
            word += '*';
            string tmp = "";
            int n = word.size();
            for (int i = 0; i < n; ++i) {
                // 分隔符在字符串开始和结尾处不用处理
                if (word[i] == separator && (i == 0 || i == n-1)) continue; 
                // 分隔符只在字符串中间出现的情况
                if (word[i] == separator || word[i] == '*') {
                    if (!tmp.empty()) {
                        res.push_back(tmp);
                        tmp = "";
                    }  
                }
                else {
                    tmp += word[i];
                }
            }
        }
        return res;
    }
};

复杂度分析

时间复杂度: O ( m × n ) O(m \times n) O(m×n) m m m 为字符串数组 words 的长度, n n n 为字符串 word 的长度。

空间复杂度: O ( n ) O(n) O(n)

方法二:getline

思路

使用 stringstream 中的 getline 操作,getline有一个重载后的版本为 getline (istream& is, string& str, char delim) 可以将输入的字符串 is 根据分隔符 delim 分割然后保存为 str

算法

class Solution {
public:
    vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
        vector<string> res;
        for (const auto& word : words) {
            stringstream ss(word);
            string sub;
            while (getline(ss, sub, separator)) {
                if (!sub.empty()) {
                    res.push_back(sub);
                }
            }
        }
        return res;
    }
};

复杂度分析

时间复杂度: O ( m × n ) O(m \times n) O(m×n) m m m 为字符串数组 words 的长度, n n n 为字符串 word 的长度。

空间复杂度: O ( n ) O(n) O(n)


写在最后

如果您发现文章有任何错误或者对文章有任何疑问,欢迎私信博主或者在评论区指出 💬💬💬。

如果大家有更优的时间、空间复杂度的方法,欢迎评论区交流。

最后,感谢您的阅读,如果有所收获的话可以给我点一个 👍 哦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wang_nn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值