最小包含兄弟子串的长度

str1 = “adabbca”;  str2 = "abc";

str1中包含str2的子串有abbc,bca,其中bca为最终结果,返回3

 1 // minLengthContain.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <string>
 7 
 8 using namespace std;
 9 int minLength(const string& str1,const string& str2)
10 {
11     int len1 = str1.length();
12     int len2 = str2.length();
13     if(len1 <= 0  || len2 <= 0 || len1 < len2)
14         return 0;
15 
16     //记账:str2 的字符看成是str1[left...right]欠的
17     int map[256];
18     for(int i = 0; i < 256;i++)
19         map[i] = 0;
20     //memset(map,0,256);//只能初始化new出来的内容
21     for(int i = 0;i < len2;i++)
22         map[str2[i]]++;
23 
24     int left = 0; 
25     int right = 0;
26     int minLen = 100;
27     int match = len2;
28     while(right < len1)
29     {
30         //str1还账,可能多还但是也通过map记着
31         map[str1[right]]--;
32         if(map[str1[right]] >=0)
33             match--;//str1还过一次之后,此处还>=0,那么该次还账为有效
34         
35         if(match == 0)
36         {
37             while(map[str1[left]] < 0)
38                 map[str1[left++]]++;//map为负,则为str1多还的,收回来
39     
40             //遇到不为负,结算。
41             minLen = min(minLen,right-left+1);
42             
43             match++;//同理进行以后的计算,更新minLen
44             map[str1[left++]]++;
45         }
46         right++;
47     }
48     return minLen == 100 ? 0 : minLen;
49 }
50 
51 int _tmain(int argc, _TCHAR* argv[])
52 {
53     string str1 = "adabbca";
54     string str2 = "acb";
55     cout<<minLength(str1,str2)<<endl;
56     system("pause");
57     return 0;
58 }
View Code

 

posted @ 2016-08-14 22:22  lp3318  阅读(243)  评论(0编辑  收藏  举报