包含字符集的最短子串

给字符串s1、s2,在s1中找包含s2里所有字符的最小子串。

类似的问题:一串首尾相连的珠子(m个),有N种颜色(N<=10),设计一个算法,取出其中一段,要求包含所有N中颜色,并使长度最短。(July,精选微软等公司数据结构+算法面试100题,40题2)

----在对s1中的子串进行判断时,对每个当前字符c,擦除在s2中的含有c的字符,这样最后s2为空时,说明该子串包含s2中的所有字符。

----使用myremove的方法,要求s2中没有重复字符,更多的方法以及更详细的介绍 :(July,程序员编程艺术第二章:字符串包含及相关问题扩展)

 1 /*
 2 *   Description:  give string s1 and s2, find the smallest
 3 * substring of s1 which contains all the characters in s2. such
 4 * as s1 is "dabbcdceacx", s2 is "abc", the substring is "abbc"
 5 */
 6 #include<iostream>
 7 #include<string>
 8 using namespace std;
 9 
10 
11 void myremove(char c, string & s2)
12 {
13     size_t found;
14     found = s2.find(c, 0);
15     if(found != string::npos)
16         s2.erase(found, 1);
17 }
18 
19 bool contain(const string &str, string s2)
20 {
21     for(int i = 0; i < str.size(); i++)
22     {
23         myremove(str[i], s2);
24         if(s2.empty())
25             return true;
26     }
27     return false;
28 }
29 
30 string myfind(const string &s1, const string &s2)
31 {
32     int N = s2.size();
33     int M = s1.size();
34     int bestSum = s1.size();
35     string bestStr = "";
36     for(int i = 0; i < M; i++)
37         for(int j = i+1; j <= M; j++)   //all the substring [i,j), with i, without j.
38         {
39             string curstr = s1.substr(i, j-i);
40             if(contain(curstr, s2))
41             {
42                 if(curstr.size() <= bestSum)
43                 {
44                     bestStr = curstr;
45                     bestSum = curstr.size();
46                 }
47             }
48         }
49     return bestStr;
50 }
51 
52 int main(int argc, char **argv)
53 {
54     string s1 = "dabbcdceacx";
55     string s2 = "abc";
56     string obj = myfind(s1, s2);
57     if(obj == "")
58         cout << "No Finding!" << endl;
59     else
60         cout << obj << endl;
61 
62     return 0;
63 }

 

转载于:https://www.cnblogs.com/dandingyy/archive/2012/10/07/2714387.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值