1+ package MustDoEasyList ;
2+
3+ import java .util .HashMap ;
4+
5+ public class FindWordsThatCanBeFormedByCharacters1160 {
6+
7+ public static int countCharacters (String [] words , String chars ) {
8+ int len = 0 ;
9+
10+ for (String word : words ) {
11+ boolean isGood = isGoodString (word , chars );
12+ if (isGood ) {
13+ len += word .length ();
14+ }
15+ }
16+ return len ;
17+ }
18+
19+ private static boolean isGoodString (String word , String chars ) {
20+
21+ HashMap <Character , Integer > map = new HashMap <>();
22+
23+ // store chars in hashmap with their character count
24+ for (char ch : chars .toCharArray ()) {
25+ if (!map .containsKey (ch )) {
26+ map .put (ch , 1 );
27+ } else {
28+ map .put (ch , map .get (ch ) + 1 );
29+ }
30+ }
31+
32+ for (char ch : word .toCharArray ()) {
33+ if (map .containsKey (ch )) {
34+ if (map .get (ch ) > 0 )
35+ map .put (ch , map .get (ch ) - 1 );
36+ else
37+ return false ;
38+ } else {
39+ return false ; // if that character is not found in map you can't
40+ // form the word from chars
41+ }
42+ }
43+ return true ;
44+ }
45+
46+ public static void main (String [] args ) {
47+ String [] words = { "cat" , "bt" , "hat" , "tree" };
48+ String chars = "atach" ;
49+
50+ System .out .println (countCharacters (words , chars ));
51+ }
52+ }
53+
54+ /*
55+ * Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6
56+ * Explanation: The strings that can be formed are "cat" and "hat" so the answer
57+ * is 3 + 3 = 6.
58+ */
0 commit comments