Skip to content

Instantly share code, notes, and snippets.

@shanehou
Last active March 4, 2016 13:01
Show Gist options
  • Save shanehou/52fd06c4adff88b9aa3e to your computer and use it in GitHub Desktop.
Save shanehou/52fd06c4adff88b9aa3e to your computer and use it in GitHub Desktop.
Alphabetically output substrings
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
void printSubstring(string s, vector<string> substrings) {
if (substrings.empty()) return;
unordered_set<string> exist;
sort(substrings.begin(), substrings.end());
for (string sub : substrings) {
for (int i = 1; i <= sub.size(); i++) {
string output = sub.substr(0, i);
if (exist.find(output) == exist.end()) {
exist.insert(output);
cout << output << endl;
}
}
}
}
void alphabeticalSubstring(string s) {
if (s.empty()) return;
if (s.size() == 1) {
cout << s << endl;
return;
}
vector<vector<string>> substringMap(26, vector<string>());
for (int i = 0; i < s.size(); i++) {
if (s[i] >= 'A' && s[i] <= 'Z') substringMap[s[i]-'A'].push_back(s.substr(i));
if (s[i] >= 'a' && s[i] <= 'z') substringMap[s[i]-'a'].push_back(s.substr(i));
}
for (int i = 0; i < 26; i++) printSubstring(s, substringMap[i]);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "Input one string as parameter" << endl;
return 1;
}
alphabeticalSubstring(string(argv[1]));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment