Difficulty : Medium
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)
注意一下String.indexOf()的用法
indexOf(int ch)
Returns the index within this string of the first occurrence of
the specified character.
indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified index.
indexOf(String s)
Returns the index within this string of the first occurrence of
the specified substring.
indexOf(String] str, int fromIndex)
Returns the index within this string of the first occurrence of
the specified substring, starting at the specified index.
這道題一開始沒看出來是用BFS來做,看了答案才發(fā)現。用一個Queue來裝s每一次去掉一個substr所剩下的newString, 同時用一個HashSet來記錄訪問過哪些newString. 寬度優(yōu)先體現在每一次都是對poll()出來的s去掉一個長度的sub, 而不是一次連續(xù)去掉很多個。這樣每一層次存下來minLength, 等最短的被poll()出來,還剩下的newString的長度就是我們要求的。
public class Solution {
/**
* @param s a string
* @param dict a set of n substrings
* @return the minimum length
*/
public int minLength(String s, Set<String> dict) {
// Write your code here
int minLength = s.length();
if (s == null || s.length() == 0){
return 0;
}
if (dict == null || dict.size() == 0){
return minLength;
}
Queue<String> queue = new LinkedList<>();
Set<String> hash = new HashSet<>();
queue.offer(s);
hash.add(s);
while (!queue.isEmpty()){
String curt = queue.poll();
for (String sub : dict){
int found = curt.indexOf(sub);
while (found != -1){
String newString = curt.substring(0, found) + curt.substring(found + sub.length(), curt.length());
if (newString.length() < minLength){
minLength = newString.length();
}
if (!hash.contains(newString)){
queue.offer(newString);
hash.add(newString);
}
found = curt.indexOf(sub, found + 1);
}
}
}
return minLength;
}
}