暴力查询即可,外面一层遍历target字符串,内层对source进行遍历,直到当前的内层遍历source中已无可匹配字符,在进行下一次source遍历,直到外层遍历结束。最终统计进行了几次内层遍历。
优化的方法:将内层遍历改为二分查找,进而衍生的需要用map存储source的每个字符对应的下标的列表。
public class test {public int shortestWay(String source, String target){Map<Character, List<Integer>> map = getCharIndexs(source);int res = 1;int index = -1;for(int i=0; i<target.length(); i++){char ch = target.charAt(i);int nextIndex = bsearch(map, ch, index);if(nextIndex == -1 && index == -1){return -1;}else if(nextIndex == -1){res++;index = -1;i--;}else{index = nextIndex;}}return res;}private Map<Character, List<Integer>> getCharIndexs(String src){Map<Character, List<Integer>> map = new HashMap<>();for(int i=0; i<src.length(); i++){char ch = src.charAt(i);map.computeIfAbsent(ch, k -> new ArrayList<>()).add(i);}return map;}private int bsearch(Map<Character, List<Integer>> map, char ch, int index){if(!map.containsKey(ch)){return -1;}List<Integer> array = map.get(ch);int l=0;int r=array.size()-1;while(l<r){int mid = l + (r-l)/2;if(array.get(mid) <= index){l = mid + 1;}else{r = mid;}}return array.get(l) > index ? array.get(l) : -1;}
}