给字符串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 }