首页 > 代码库 > 九章算法基础班

九章算法基础班

Remove Substrings 

技术分享
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.

Have you met this question in a real interview? Yes
Example
Given s = ccdaabcdbb, substrs = ["ab", "cd"]
Return 2

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

思路:很容易想到贪心,能尽量削减原串就削减原串,但是贪心是错误的,反例:"abcabd", ["ab","abcd"]

   用DFS,对于dict中的每一个子串,在原串中找到匹配的该串的索引,并截取原字符串,更新结果,将截取后的字符串加入到队列中(增加一个set来避免相同的串重复加入到队列)以便下一次循环,然后从该索引后面的一个位置开始再找与该子串匹配的索引,重复上述过程。

技术分享
 1 public class Solution {
 2     /**
 3      * @param s a string
 4      * @param dict a set of n substrings
 5      * @return the minimum length
 6      */
 7     public int minLength(String s, Set<String> dict) {
 8         // Write your code here
 9         if (s == null) {
10             return 0;
11         }
12         if (s.length() == 0 || dict == null || dict.size() == 0) {
13             return s.length();
14         }
15         int result = s.length();
16         Queue<String> queue = new LinkedList<>();
17         Set<String> set = new HashSet<>();
18         queue.offer(s);
19         set.add(s);
20         while (!queue.isEmpty()) {
21             String str = queue.poll();
22             for (String subStr : dict) {
23                 int index = str.indexOf(subStr);
24                 while (index != -1) {
25                     String newStr = str.substring(0, index)
26                         + str.substring(index + subStr.length(), str.length());
27                     if (!set.contains(newStr)) {
28                         set.add(newStr);
29                         queue.offer(newStr);
30                         result = Math.min(result, newStr.length());
31                     }
32                     index = str.indexOf(subStr, index + 1);
33                 }
34             }
35         }
36         return result;
37     }
38 }
View Code

 

九章算法基础班