Visit this to view the content of this question.
Java code:
public static String minWindow (String S, String T)
{
if ( S.length() < T.length() || T.isEmpty())
return "";
int min = 0;
int start = 0;
int end = 0;
HashMap<String, Queue<Integer>> window = new HashMap<String, Queue<Integer>>();
ArrayList<Integer> index = new ArrayList<Integer> ();
ArrayList<String> tmpT = new ArrayList<String> ();
for (int j = 0; j < T.length(); j++)
{
tmpT.add(T.substring(j, j+1));
}
for (int i = 0; i < S.length(); i++)
{
if (T.contains( S.substring(i, i+1)))
{
if (tmpT.contains(S.substring(i, i+1)))
{
Queue<Integer> tmp = window.get(S.substring(i, i+1));
if (tmp == null)
{
tmp = new LinkedList<Integer> ();
}
tmp.add(i);
window.put(S.substring(i, i+1), tmp );
tmpT.remove(S.substring(i,i+1));
index.add(i);
if (tmpT.isEmpty())
{
min = index.get( index.size() - 1)- index.get(0);
start = index.get(0);
end = index.get( index.size() - 1 );
}
}
else
{
Queue<Integer> tmp = window.get(S.substring(i, i+1));
tmp.add(i);
index.remove( index.indexOf(tmp.poll()));
index.add(i);
window.put(S.substring(i, i+1), tmp);
}
/**
* update the min widow.
*/
if (tmpT.isEmpty())
{
if ( min > index.get( index.size() - 1)- index.get(0) )
{
start = index.get(0);
end = index.get(index.size() - 1);
min = index.get( index.size() - 1)- index.get(0);
}
}
}
}
if( !tmpT.isEmpty() )
return "";
else return S.substring(start, end+1);
}