码迷,mamicode.com
首页 > Windows程序 > 详细

76 Minimum Window Substring

时间:2015-07-10 09:34:35      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:leetcode

76 Minimum Window Substring

链接: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.

Hide Tags Hash Table Two Pointers String

找S字符串中,含有所有T字符串字符的最小子串。想到的办法从前往后遍历,先找到一个子串,有了两个指针,一个指针在头部,一个指针在尾部。然后头部向前移动,直到不满足含有所有T字符串字符的条件,然后再移动尾部指针,直到满足含有所有T字符串字符的条件。在找到的所有子串中找到最小的子串就可以了。

class Solution {
public:
    bool tablevaild(int *t1,int *t2)
    {
        for(int i=0;i<128;i++)
       {
          if(t1[i]>t2[i])
              return false;
       }
       return true;
    }
    string minWindow(string s, string t) 
    {
        int table1[128],table2[128];
        memset(table1,0,128*4);
        memset(table2,0,128*4);

        int length=t.length();
        string result="";
        int i,j;
        for(i=0;i<length;i++)
           table1[t[i]]++;

        i=j=s.find_first_of(t);

        for(;i<=(int)s.length()-length;i++)
        {
            if(table1[s[i]]==0)
                continue;

            if(tablevaild(table1,table2))
            {
             if(result==""||result.length()>j-i)
                result=s.substr(i,j-i);
            }
            else
            {
            for(;j<(int)s.length();j++)
            {
                    table2[s[j]]++;
                if(tablevaild(table1,table2))
                {
                    j++;
                    if(result==""||result.length()>j-i)
                     result=s.substr(i,j-i);
                    break;
                }
            }
            }
            table2[s[i]]--;
        }
        return result;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

76 Minimum Window Substring

标签:leetcode

原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46822025

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!