Last active
April 4, 2018 02:22
-
-
Save zhuangh/321ddca65b19afff18846e82ef859c47 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<string> | |
#include<iostream> | |
#include<vector> | |
using namespace std; | |
class ShortPalindromes{ | |
public: | |
string solve(const string & s, int i, int j, | |
vector<vector<string>> & mem){ | |
if(i>j) return ""; | |
if(i==j) return mem[i][j] = s[i]; | |
if(mem[i][j] != "") return mem[i][j]; | |
string res; | |
string prefix = s[j] + solve(s, i, j-1, mem) + s[j]; | |
string suffix = s[i] + solve(s, i+1, j, mem) + s[i]; | |
if(prefix.size() != suffix.size()){ | |
if(prefix.size() < suffix.size()) res = prefix; | |
else res = suffix; | |
} | |
else{ | |
if(prefix < suffix) res = prefix; | |
else res = suffix; | |
} | |
if(s[i] == s[j]) { | |
res = s[i] + solve(s, i+1, j-1, mem) + s[j]; | |
} | |
return mem[i][j] = res; | |
} | |
string shortest(const string & base){ | |
int n = base.size(); | |
vector<vector<string>> mem(n, vector<string>(n, "")); | |
return solve(base, 0, base.size()-1, mem); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment