Skip to content

Instantly share code, notes, and snippets.

@MitI-7
Created May 11, 2015 06:37
Show Gist options
  • Save MitI-7/6d80218cbb58a7af8492 to your computer and use it in GitHub Desktop.
Save MitI-7/6d80218cbb58a7af8492 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
map<pair<string, string>, int> memo;
int longestCommonSubsequence(string s, string t) {
if (s.size() == 0 || t.size() == 0) { return 0; }
if (memo.find(make_pair(s, t)) != memo.end()) {
return memo[make_pair(s, t)];
}
string s1 = s.substr(0, s.size() - 1);
string t1 = t.substr(0, t.size() - 1);
if (s[s.size() - 1] == t[t.size() - 1]) {
return memo[make_pair(s, t)] = longestCommonSubsequence(s1, t1) + 1;
}
else {
return memo[make_pair(s, t)] = max(longestCommonSubsequence(s1, t), longestCommonSubsequence(s, t1));
}
}
int main(int argc, char *argv[]) {
string s = "abcde", t = "aobpc";
cout << longestCommonSubsequence(s, t) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment