I want to get all the possible strings-1 character of a string. For examples for the string A13 I will get A1, A3 and 13. I made a function that has a quadratic time complexity and I want to know if there’s a technic that can make it more efficient. This is the code:
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> generateSubstrings(const std::string& inputString) {
std::vector<std::string> substrings;
for (size_t i = 0; i < inputString.length(); ++i) {
std::string substring = inputString.substr(0, i) + inputString.substr(i + 1);
substrings.push_back(substring);
}
return substrings;
}
int main() {
std::string inputString = "A13";
std::vector<std::string> result = generateSubstrings(inputString);
for (const std::string& substring : result) {
std::cout << substring << std::endl;
}
return 0;
}
Given that the output has O(n^2)
characters, you're not going to be able to output it all in less than O(n^2)
time. It's possible to emplace the strings, one after the other, into the same buffer in only O(n)
time total, but that wouldn't be useful because you couldn't consume them in less than O(n^2)
time.