贴个pattern字符串有重复字符的解法, 是dek,cpp1等大牛的解法的扩展。
#include
#include
#include
#include
using namespace std;
#define INT_MAX 2147483647
#define INT_MIN -2147483648
class MinWindowSolution
{
public:
struct TreeNode
{
TreeNode *parent;
int val;
vector children;
TreeNode(int i, TreeNode *p) : val(i), parent(p){}
};
void FindMinWindow_Tree(const vector& input , const vector&
query , int& nStart, int& nEnd){
nStart = nEnd = -1;
if (sizeof(query) > sizeof(input) || query.size() <= 0) return;
int nMin = INT_MAX;
unordered_map* > pos;
for (int i = 0; i < query.size(); ++i)
pos[query[i]] = new deque();
bool bFilled = true;
for (int j = 0; j < input.size(); ++j){
if (pos.find(input[j]) != pos.end()){
auto q = pos[input[j]];
q->push_front(j);
pos[input[j]] = q;
if (q->size() <= 0)
bFilled = false;
}
}
if (!bFilled) return;
TreeNode *root = new TreeNode(INT_MIN, 0);
deque *pRoot = reinterpret_cast *>(pos.at(query[0]));
for (int s=0; s< pRoot->size(); ++s){
int v = pRoot->at(s);
root->children.push_back(new TreeNode(v, root));
}
vector lst = root->children;
nMin = INT_MAX;
for (int k = 1; k < query.size(); ++k){
vector tmpList;
for(int r = 0; r < lst.size(); ++r){
TreeNode *pNode = lst[r];
deque *pDeque = reinterpret_cast *>(pos.at(
query[k]));
for (int t = 0; t < pDeque->size(); ++t){
if (pDeque->at(t) <= pNode->val) continue;
TreeNode *pNewNode = new TreeNode(pDeque->at(t), pNode);
pNode->children.push_back(pNewNode);
int nfindex, nlindex;
if (k == query.size()-1 ){
if(nMin > pathLength(pNewNode, nfindex, nlindex)){
nMin = pathLength(pNewNode, nfindex, nlindex);
nStart = nfindex;
nEnd = nlindex;
}
}
}
tmpList.insert(tmpList.end(), pNode->children.begin(), pNode
->children.end());
}
lst = tmpList;
}
}
int pathLength(TreeNode *tnSource, int& nFirstIndex, int& nLastIndex)
{
nLastIndex = nFirstIndex = -1;
nLastIndex = tnSource->val;
TreeNode *temp = tnSource;
TreeNode *trailing = 0;
while (temp->parent != 0){
trailing = temp;
temp = temp->parent;
}
nFirstIndex = trailing->val;
if (nLastIndex > nFirstIndex) //all matched and in good order
return nLastIndex - nFirstIndex + 1;
return INT_MAX;
}
static void TestMinWindowSolution()
{
int inputArray[] = { 1, 7, 8, 19, 3, 2, 2, 38, 25, 39, 14, 0,
2, 2, 87, 39, 14 };
int queryArray[] = { 2, 2, 39, 14 };
std::vector input(std::begin(inputArray), std::end(inputArray));
vector query(std::begin(queryArray), std::end(queryArray));
int nStart, nEnd;
MinWindowSolution *sol = new MinWindowSolution();
sol->FindMinWindow_Tree(input, query, nStart, nEnd);
assert(nStart == 12 && nEnd == 16);
}
};