Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6f4b639

Browse files
Priyanka94suthaarPriyanka Suthaar
and
Priyanka Suthaar
authored
Adding solution for Day 22 Challenge Problem (#176)
Co-authored-by: Priyanka Suthaar <priyanka94suthaar@gmail.com>
1 parent 7d9d0a5 commit 6f4b639

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /