Remove Substrings - Lintcode

Given a stringsand 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

Given s =ccdaabcdbb, substrs =["ab", "cd"]
Return2

Explanation:
ccdaabcdbb->ccdacdbb->cabb->cb(length = 2)

Analysis:

A few experiments should have shown that the iteration on removing substr from s won't work because the order of removal matters. Take "ab, "abcd" on "ababcd", removing "ab" from "ababcd" will end up with "cd" which cannot be removed further. Therefore the nature answer to this is saving the result of each removal and fetch it into the removing process again. During the removing process, check the min length of the string.

*when new items are added to collections in iteration, queue should be used.

public int minLength(String s, Set<String> dict) {        
    if (s.length() == 0) {
        return 0;
    }

    Queue<String> queue = new LinkedList<String>();
    HashSet<String> set = new HashSet<String>();        
    queue.offer(s);

    int result = s.length();

    while (!queue.isEmpty()) {
        String str = queue.poll();

        for (String word : dict) {
            int idx = str.indexOf(word);
            while (idx > -1) {
                String newStr = str.substring(0, idx) + str.substring(idx + word.length());

                if (!set.contains(newStr)) {
                    set.add(newStr);
                    queue.offer(newStr);
                }
                result = Math.min(result, newStr.length());                    
                idx = str.indexOf(word, idx + 1);
            }
        }
    }

    return result;
}

results matching ""

    No results matching ""