Leetcode-minimum window substring-Minimum Windows sub-string-sliding window algorithm (ruler method)

Source: Internet
Author: User

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

Under the constraints of linear complexity, consider using the sliding window method. The idea of this approach is to maintain a window that expands to the right edge to meet the constraints. The left edge of the window shrinks to minimize it.

Note that this topic may be an implementation of a typical sliding window approach. The outer loop moves the left boundary I, and the loop expands the right boundary p to meet the constraints. And both inside and outside have termination possibilities.

Use two map and a count variable to quickly statistic the conditions of the condition to be satisfied.

Class Solution {Public:int n,m;string Minwindow (String S, String T) {map <char,int> cm;map <char,int> stat;n=s . Length (); M=t.length (); for (int i=0;i<m;i++) {if (Cm.find (T[i]) ==cm.end ()) {cm[t[i]]=1;} else{cm[t[i]]++;} stat[t[i]]=0;} int Res=numeric_limits<int>::max (); typedef pair <int,int> Scpair;scpair minw;int q=0;int count=0;for (int i =0;i<n;i++) {bool Endflag=false;while (count<m) {q++;if (q>n) {endflag=true;break;} if (Cm.find (S[q-1]) ==cm.end ()) {continue;} if (Stat[s[q-1]]<cm[s[q-1]]) {count++;} stat[s[q-1]]++;} if (Endflag) {break;} if (res > Q-i) {res=q-i;minw=scpair (i,q);    } if (Cm.find (S[i]) ==cm.end ()) {continue;} Stat[s[i]]--;if (Stat[s[i]]<cm[s[i]]) {count--;}} if (res>n) {return "";} No Winreturn s.substr (Minw.first,minw.second-minw.first);};

  

Leetcode-minimum window substring-Minimum Windows sub-string-sliding window algorithm (ruler method)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.