LintCode 1587: String Segmentation

1587. String Segmentation

Now there is a string, the first character represents the first-level separator, separating different key-value pairs, the second character represents the second-level separator, separating key and value and the next string represents the string to be processed.

Please give all valid key-value pairs.

 

Example

Example1

input:"#:a:3#b:8#c:9"

output:[["a","3"],["b","8"],["c","9"]]

Example 2

input:"#:aa:3#b:853#:9"

output:[["aa","3"],["b","853"]]

Notice

Valid key-value pairs are key-value pairs that neither key nor value is empty.

The problem ensures that the separator is not letters or numbers, and the string to be processed contains only two types of separators, lowercase letters and numbers.

There can be at most one second-level separator between two first-level separators.

The length of the string in problem is no more than 1000.

解法1:

class Solution {
public:
    /**
     * @param str: the string need to be processed
     * @return: all the valid key-value pairs.
     */
    vector<vector<string>> StringSeg(string &str) {
        if (str.size() <= 2) return {{}};
        char first_level_sep = str[0];
        char second_level_sep = str[1];
        
        stringstream ss(str.substr(2));
        vector<string> tokens;
        string buf;
        
        while(getline(ss, buf, first_level_sep)) {
            tokens.push_back(buf);
        }
        
        vector<vector<string>> result;
        int len = tokens.size();
        for (int i = 0; i < len; ++i) {
            string key, value;
            int pos = tokens[i].find_first_of(second_level_sep);
            if (pos == std::string::npos) continue;
            key = tokens[i].substr(0, pos);
            value = tokens[i].substr(pos + 1);
            if (key.size() != 0 && value.size() != 0) {
                result.push_back({key, value});
            }
        }
        
        return result;
    }
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值