[leetcode] Minimum Window Substring

来源:互联网 发布:爱情是一场梦网络歌手 编辑:程序博客网 时间:2024/06/18 08:19

https://leetcode.com/problems/minimum-window-substring/

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

class Solution {public:    string minWindow(string s, string t) {if(s.size() < t.size() || "" == t) {return "";}int cint[256] = {0};for(int i=0; i<t.size(); ++i) {++cint[t[i]];}string minWin = "";int findins[256] = {0};int find = 0, n = t.size();queue<int> idxes;int st = -1, ed = -2;//ed < st means no window exits.for(int i=0; i<s.size(); ++i) {char c = s[i];if(cint[c]) {idxes.push(i);if(st < 0) { // st not initst = i;}ed = i;++findins[c];if(findins[c] <= cint[c]) {// first find s[i]++find;} else {c = s[st];while(!idxes.empty() && findins[c] > cint[c]) {idxes.pop();--findins[c];st = idxes.front();c = s[st];}}if(find == n && ("" == minWin || ed - st + 1 < minWin.size())) {minWin = s.substr(st, ed-st+1);}} // if cint[s[i]]}return minWin;    }};

public class Solution {    public String minWindow(String s, String t) {if (s == null || s.length() == 0 || t == null || t.length() == 0) {return "";}int[] tHas = new int[256];for (int i = 0; i < t.length(); ++i) {++tHas[t.charAt(i)];}String minWin = "";int[] sFnd = new int[256];int find = 0, n = t.length();Queue<Integer> idxes = new LinkedList<Integer>();int st = -1, ed = -2; // ed < st means no window exits.for (int i = 0; i < s.length(); ++i) {char c = s.charAt(i);if (tHas[c] > 0) {idxes.offer(i);if (st < 0) { // st not initst = i;}ed = i;++sFnd[c];if (sFnd[c] <= tHas[c]) {// first find s[i]++find;} else {c = s.charAt(st);while (!idxes.isEmpty() && sFnd[c] > tHas[c]) {idxes.poll();--sFnd[c];st = idxes.peek();c = s.charAt(st);}}if (find == n && ("".equals(minWin) || ed - st + 1 < minWin.length())) {minWin = s.substring(st, ed+1);}} // if cint[s[i]]}return minWin;}}


0 0
原创粉丝点击