subsequence
Explanation :
Step 1: Iterate over the entire String
Step 2: Iterate from the end of string
in order to generate different substring
add the subtring to the list
Step 3: Drop kth character from the substring obtained
from above to generate different subsequence.
Step 4: if the subsequence is not in the list then recur.
Below is the implementation of the approach.
// Java Program to print all subsequence of a
// given string.
import java.util.HashSet;
public class Subsequence {
// set to store all the subsequences
static HashSet<String> st = new HashSet<>();
// It computes all the subsequence of an string
static void subsequence(String str)
{
// iterate over the entire string
for (int i = 0; i < str.length(); i++) {
// iterate from the end of the string
// to generate substrings
for (int j = str.length(); j > i; j--) {
String sub_str = str.substring(i, j);
if (!st.contains(sub_str))
st.add(sub_str);
// drop kth character in the substring
// and if its not in the set then recur
for (int k = 1; k < sub_str.length() - 1; k++) {
StringBuffer sb = new StringBuffer(sub_str);
// drop character from the string
sb.deleteCharAt(k);
if (!st.contains(sb))
;
subsequence(sb.toString());
}
}
}
}
// Driver code
public static void main(String[] args)
{
String s = "aabc";
subsequence(s);
System.out.println(st);
}
}
substring
We can run three nested loops, the outermost loop picks starting character, mid loop considers all characters on right of the picked character as ending character of substring. The innermost loop prints characters from currently picked starting point to picked ending point.
// C++ program to print all possible
// substrings of a given string
#include<bits/stdc++.h>
using namespace std;
// Function to print all sub strings
void subString(char str[], int n)
{
// Pick starting point
for (int len = 1; len <= n; len++)
{
// Pick ending point
for (int i = 0; i <= n - len; i++)
{
// Print characters from current
// starting point to current ending
// point.
int j = i + len - 1;
for (int k = i; k <= j; k++)
cout << str[k];
cout << endl;
}
}
}
// Driver program to test above function
int main()
{
char str[] = "abc";
subString(str, strlen(str));
return 0;
}