Question:
Find the subsequences of string in lexicographically sorted order in C++


Summary

Using a string s as input and a method called AllPossibleStrings, a class called Solution can produce a vector of strings that contains every possible substring of the input string s.


Solution

class Solution{

public:

vector<string> AllPossibleStrings(string s){

    vector<string> ans;

    ans.push_back("");

    for(auto ch:s){

        int n=ans.size();

        for(int i=0;i<n;i++){

            string str = ans[i];

            str.push_back(ch);

            ans.push_back(str);

        }

    }

    ans.erase(ans.begin());

    sort(ans.begin(),ans.end());

    return ans;

}

};


Explanation

  • The Solution class contains the definition for the AllPossibleStrings function. Since it is declared with a public access specifier, users outside of the class are able to access it.

  • Ans, a vector, is initialized within the method. Every potential substring of the input string s will be stored in this vector. It starts off with an empty string.

  • Using a range-based for loop, the method iterates through each character ch in the input string s.


Suggested blogs:

>Find the number of pairs of elements whose sum is equal to K using C++

>How to check whether string is palindrome or not using C++

>How to determine the smallest possible size of a vertex cover using C++

>How to reverse the first K elements of queue using C++

>How to find duplicate rows in a binary matrix using C++

>How to find the total number of special sequences possible using C++

>How to Reverse array in groups? C++

>How to represent the maximum value in knapsack using C++


Nisha Patel

Nisha Patel

Submit
0 Answers