I'm trying to solve a programming challenge for fun. The programming challenge is here and my solution for the same can be found here.
It currently causes an exceeded time limit.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int a[25001];
bool is_edit_distance_one(string one, string two) {
if ( one.size() == two.size() ) {
bool found_diff = false;
for ( int i = 0 ; i < one.size(); i++ ) {
if ( found_diff && one[i] != two[i] ) return false;
else if ( one[i] != two[i] ) found_diff = true;
}
return true;
}
else if ( (one.size() - two.size()) == 1 && one.find(two) != string::npos )
return true;
else if ( (two.size() - one.size()) == 1 && two.find(one) != string::npos )
return true;
return false;
}
map<string, bool> generate(string one) {
map<string, bool> edits;
string all_chars = "abcdefghijklmnopqrstuvwxyz";
// Generate all strings by adding another letter
for ( int i = 0; i <= one.size(); i++ ) {
for ( int j = 0; j < all_chars.size(); j++ ) {
// split the string at i
string temp = one.substr(0, i);
temp += all_chars[j];
temp += one.substr(i, one.size()-i);
edits[temp] = true;
}
}
// Generate all strings by deleting a letter
for ( int i = 0; i < one.size(); i++ ) {
string temp = one.substr(0, i);
temp += one.substr(i+1, one.size()-i);
edits[temp] = true;
}
// Generate all strings by changing a letter
for ( int i = 0; i < one.size(); i++ ) {
for ( int j = 0; j < all_chars.size(); j++ ) {
string temp = one.substr(0, i);
temp += all_chars[j];
temp += one.substr(i+1, one.size()-i);
edits[temp] = true;
}
}
return edits;
}
int main() {
string s;
int i = 0;
int l;
vector<string> all;
while ( cin >> s ) {
a[i] = 0;
all.push_back(s);
l = all.size();
for ( int i = 0; i < l-1; i++ ) {
map<string, bool> edits = generate(all[l-1]);
if ( edits[all[i]] ) {
a[l-1] = max(a[i]+1, a[l-1]);
}
}
}
sort(a, a+l);
cout << a[l-1] + 1 << endl;
}
Instead of calculating the edit distance between strings (using is_edit_distance_one
), I'm generating a map with all possible edit strings of a string and checking if previous strings are present in it (using the function "generate").
- Are there any implementation level mistakes that I'm making that's slowing it down?
- Any particular data structure I should/should not be using?
- Any other algorithm I could use to speed things up?
fog -> log -> dig -> dog -> fig -> fin -> fine -> wine
\$\endgroup\$