LintCode 624: Remove Substrings (BFS经典题)

  1. 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中,然后再继续处理。
注意:

  1. 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值