碰到这样一道算法题:给定一个字符串,比如: cadacacbedffffreaaawc ,然后给定两个字符为f,c ,那么最短子串的长度为5。因为子串有cbedf,freaaawc. 这篇博客考虑的比较简单,是只有两个字符的情况,我会在后续的博客中讲解如果需要包含多个字符那么应该如何处理。本篇的代码上传至 https://github.com/chenyufeng1991/MaxLengthSubString 。
这里的实现思路比较简单,对string进行一次遍历,分别记录出现字符a,字符b的下标index,分别存储到两个数组或者vector中。那么现在在vectorA中存储的下标位置就是出现a字符的所有位置,vectorB中存储的下标位置就是出现b字符的所有位置。最后即可通过循环查找两者最接近的差值即可。核心代码实现如下:
cout << "请输入字符串:"; string stringIn; cin >> stringIn; cout << "请输入两个字符:"; char a, b; cin >> a >> b; vector<int> vectorA; vector<int> vectorB; for (int i = 0; i < stringIn.size(); i++) { if (stringIn[i] == a) { vectorA.push_back(i); } if (stringIn[i] == b) { vectorB.push_back(i); } } if (vectorA.empty() || vectorB.empty()) { cout << "最短子串为:0"<< endl; } else { int minLength = (int)stringIn.size(); for (int i = 0; i < vectorA.size(); i++) for (int j = 0; j < vectorB.size(); j++) { minLength = min(minLength, abs(vectorA[i]-vectorB[j]) + 1); } cout << "最短子串为:"<< minLength << endl; }