- Remove Substrings
中文English
Given a string s and a set of n substrings. You are supposed to remove every instance of those n substrings from s so that s is of the minimum length and output this minimum length.
Example
Example 1:
Input:
“ccdaabcdbb”
[“ab”,“cd”]
Output:
2
Explanation:
ccdaabcdbb -> ccdacdbb -> cabb -> cb (length = 2)
Example 2:
Input:
“abcabd”
[“ab”,“abcd”]
Output:
0
Explanation:
abcabd -> abcd -> “” (length = 0)
解法1:BFS
这题很难想到是用BFS。关键思想就是把所有可能替换的结果都放到queue中,然后再继续处理。
注意:
- for里面一定要是while(),如果只是用if()的话,结果不对。因为删除的顺序会对结果有影响。
比如说s= “abcabd”,[“ab”, “abcd”]。
注意"ab“在两处都有,所以两个地方都要考虑,即我们应该把new_s = “cabd"和”abcd“都放入queue中。这样,最优结果是从"abcd"中得到的(因为匹配"abcd”),这样最终结果是0。如果只放"cabd",那它又与"ab"匹配,最终剩下"cd",最终结果就是2,不对。
代码如下:
class Solution {
public:
/*
* @param s: a string
* @param dict: a set of n substrings
* @return: the minimum length
*/
int minLength(string &s, unordered_set<string> &dict) {
int N = s.size();
if (N == 0) return 0;
queue<string> q;
unordered_set<string> hashSet;
int minLen = N;
q.push(s);
hashSet.insert(s);
while(!q.empty()) {
string s = q.front();
q.pop();
for (auto str : dict) {
int pos = s.find(str);
while(pos != -1) {
//if (pos != -1) {
string new_s = s.substr(0, pos) + s.substr(pos + str.size());
if (hashSet.find(new_s) == hashSet.end()) {
q.push(new_s);
hashSet.insert(new_s);
minLen = min(minLen, (int)new_s.size());
}
pos = s.find(str, pos + 1); //important!
}
}
}
return minLen;
}
};