|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +public class Day22StrSubsequenceCount { |
| 4 | + public static void main(String[] args){ |
| 5 | + String str = "abacde"; |
| 6 | + String[] words = {"a", "bb", "acd", "ace"}; |
| 7 | + int count = numMatchingSequence(str,words); |
| 8 | + System.out.println(count); |
| 9 | + } |
| 10 | + |
| 11 | + public static int numMatchingSequence(String str, String[] words){ |
| 12 | + int result = 0; |
| 13 | + Map<Character, List<Integer>> map = new HashMap<>(); |
| 14 | + |
| 15 | + for(int i=0; i<str.length(); i++){ |
| 16 | + map.putIfAbsent(str.charAt(i), new ArrayList<>()); |
| 17 | + map.get(str.charAt(i)).add(i); // It will add size of that character in map (occurence) |
| 18 | + } |
| 19 | + |
| 20 | + for (String word : words) { |
| 21 | + if (match(str, word, map, 0)) { |
| 22 | + result++; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + return result; |
| 27 | + } |
| 28 | + |
| 29 | + private static boolean match(String S, String word, Map<Character, List<Integer>> map, int startIndex) { |
| 30 | + if (word.length() == 0) return true; |
| 31 | + if (!map.containsKey(word.charAt(0))) return false; |
| 32 | + for (int start : map.get(word.charAt(0))) { |
| 33 | + if (start < startIndex) continue; |
| 34 | + String newWord = word.substring(1, word.length()); |
| 35 | + return match(S, newWord, map, start + 1); |
| 36 | + } |
| 37 | + |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | +} |
0 commit comments