1. 最大上升子序列
template<typename T>
vector<T> longestIncreasingSubsequence(vector<T> &vec)
{
vector<T> res; //res中只保存递增数列
if (vec.empty()) return res;
for (auto iter = vec.begin(); iter != vec.end(); ++iter)
{
if (res.empty() || res.back() <= *iter) //如果*iter比res中的最后一个数大,直接push_end
res.push_back(*iter);
else //否则在res中向前查找,找到第一个比*iter小的数,并替换为*iter
{
auto rp = res.rbegin();
while (rp != res.rend() && *rp > *iter) ++rp;
if (rp != res.rend()) *rp = *iter; //如果都比*iter大,则不用替换
}
}
return res;
}
2. 最长相同子序列
目前这个写法还比较笨拙
string longestSameSubsequence(string &str)
{
if (str.empty()) return str;
int maxlen = 0;
int len = 0;
int pos = str.length();
char last = 0;
//倒序搜索,方便pos取最长相等子序列的开始位置
for (int i = str.length() - 1; i >= 0; --i)
{
if (i == str.length() - 1)
{
len = 1;
maxlen = 1;
pos = i;
last = str[i];
}
else
{
if (last == str[i]) ++len;
else
{
if (maxlen < len)
{
maxlen = len;
pos = i + 1;
}
last = str[i];
len = 1;
}
}
}
if (maxlen < len)
{
maxlen = len;
pos = 0;
}
string res(str.begin() + pos, str.begin() + pos + maxlen);
return res;
}