#include <iostream> #include <iomanip> #include <map> #include <string> #include <conio.h> /* Print all the substrings of a given string. Is there any solution better than O(2^n) */ std::map<std::string, int> substrings; std::map<std::string, int>::iterator it; /* A O(2^n) algorithm ! recurrence: T(n) = 2T(n-1) */ void subStrings(std::string s) { int slice = s.length()-1; // add string to substrings substrings[s] = 1; if(slice == 0) return; // base case ! single character int pos = 0; while(true) { std::string tmp = s.substr(pos, slice); subStrings(tmp); pos++; if(pos+slice > s.length()) break; } } /* A O(n^2) algorithm - bubble sort like explanation */ void subStrings1(std::string s) { for(int i = 0; i < s.length(); i++) { for(int j = 1; j <= s.length()-i; j++) std::cout << s.substr(i,j) << std::endl; } } int main() { std::string s = "ABCDEF"; subStrings(s); for(it = substrings.begin(); it != substrings.end(); it++) std::cout << (*it).first << std::endl; subStrings1(s); getch(); }
Yet another blog from yet another software engineer - a collection of my thoughts and some snippets of code I write (mainly for my later reference). If you find this useful, lets discuss in comments.
December 27, 2012
All sub-strings of a string
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment