其他分享
首页 > 其他分享> > 1087 花括号展开

1087 花括号展开

作者:互联网

题目描述:
我们用一个特殊的字符串 S 来表示一份单词列表,之所以能展开成为一个列表,是因为这个字符串 S 中存在一个叫做「选项」的概念:
单词中的每个字母可能只有一个选项或存在多个备选项。如果只有一个选项,那么该字母按原样表示。
如果存在多个选项,就会以花括号包裹来表示这些选项(使它们与其他字母分隔开),例如 “{a,b,c}” 表示 [“a”, “b”, “c”]。
例子:"{a,b,c}d{e,f}" 可以表示单词列表 [“ade”, “adf”, “bde”, “bdf”, “cde”, “cdf”]。
请你按字典顺序,返回所有以这种方式形成的单词。

示例 1:
输入:"{a,b}c{d,e}f"
输出:[“acdf”,“acef”,“bcdf”,“bcef”]

示例 2:
输入:“abcd”
输出:[“abcd”]

提示:
1 <= S.length <= 50
你可以假设题目中不存在嵌套的花括号
在一对连续的花括号(开花括号与闭花括号)之间的所有字母都不会相同

方法1:
主要思路:解题链接汇总
(1)先将字符串进行分解,获得每个位置上的可能的字符,使用 vector<vector> chars;进行存储;
(2)使用dfs获得各个可能组成的字符串;

class Solution {
public:
	//生成各个可能的字符串
    void dfs(vector<vector<char>>&chars,string&str,vector<string>&res,int index){
        if(index==chars.size()){
            res.push_back(str);
            return;
        }
        for(int i=0;i<chars[index].size();++i){
            str[index]=chars[index][i];
            dfs(chars,str,res,index+1);
        }
    }
    vector<string> expand(string S) {
        vector<vector<char>> chars;
        int index=0;
        //将字符串进行分解
        while(index<S.size()){
            if(S[index]==','){
                ++index;
                continue;
            }
            chars.push_back({});
            if(S[index]=='{'){
                ++index;
                while(S[index]!='}'){
                    if(S[index]!=','){
                        chars.back().push_back(S[index]);
                    }
                    ++index;
                }
            }
            else{
                chars.back().push_back(S[index]);
            }
            ++index;
        }
        string str(chars.size(),' ');
        vector<string>res;
        dfs(chars,str,res,0);
        //字典序输出
        sort(res.begin(),res.end());
        return res;
    }
};

标签:1087,index,res,chars,back,括号,vector,str,展开
来源: https://blog.csdn.net/weixin_44171872/article/details/113789355