数据结构笔记--字符串经典高频题

1--打印字符串的全部子序列

题目:

        返回一个字符串的全部子序列(包括空串);

主要思路:

        暴力枚举是否加入当前字符;

#include <iostream>
#include <vector>
#include <string>

class Solution{
public:
    std::vector<std::string> Printstr(std::string str){
        if(str.length() == 0) return res;
        process(str, 0, "");
        return res;
    }

    void process(std::string str, int i, std::string cur_str){
        if(i == str.length()){
            res.push_back(cur_str);
            return;
        }
        process(str, i+1, cur_str+str[i]); // 加入当前字符
        process(str, i+1, cur_str); // 不加入当前字符
    }

private:
    std::vector<std::string> res;

};


int main(int argc, char *argv[]){
    Solution S1;
    std::string test = "abc";
    std::vector<std::string> res = S1.Printstr(test);
    for(std::string str : res) std::cout << str << std::endl;
}

2--字符串的全排列

主要思路:

        利用全排列遍历字符串,注意重复字符在树层上的剪枝(但要保留重复字符在树枝上的排列) 

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

class Solution {
public:
    std::vector<std::string> permutation(std::string s){
        if(s.length() == 0) return res;
        std::vector<bool> used(s.length(), false);
        std::sort(s.begin(), s.end());
        std::string tmp = "";
        process(s, 0, tmp, used);
        return res;
    }

    void process(std::string str, int idx, std::string tmp, std::vector<bool> used){
        if(idx == str.length()){
            res.push_back(tmp);
            return;
        }
        for(int i = 0; i < str.length(); i++){
            if(used[i] == true) continue; // 该字符已使用
            // 去除树层重复字符
            if(i > 0 && str[i] == str[i-1] && used[i-1] == true) continue;
            used[i] = true;
            process(str, idx + 1, tmp + str[i], used);
            // 回溯
            used[i] = false;
        }
    }

private:
    std::vector<std::string> res;
};

int main(int argc, char *argv[]){
    std::string test = "aab";
    Solution S1;
    std::vector<std::string> res = S1.permutation(test);
    for(std::string str : res) std::cout << str << std::endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43863869/article/details/132304548