Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit b0fd3cc

Browse files
committed
#1160 拼写单词
1 parent 2a2514f commit b0fd3cc

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package hashmap;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* @author liangqian0723@gmail.com
8+
* @since 2020/3/17 11:10 PM
9+
*/
10+
public class LC_1160_FindWordsThatCanBeFormedByCharacters {
11+
public int countCharacters(String[] words, String chars) {
12+
int count = 0;
13+
HashMap<Character, Integer> charMap = getCharCount(chars);
14+
for (String word : words) {
15+
HashMap<Character, Integer> charCountMap = getCharCount(word);
16+
count += compareChar(charCountMap, charMap) != 0 ? word.length() : 0;
17+
}
18+
return count;
19+
}
20+
21+
private int compareChar(HashMap<Character, Integer> wordCountMap, HashMap<Character, Integer> charMap) {
22+
for (Map.Entry<Character, Integer> entry : wordCountMap.entrySet()) {
23+
char key = entry.getKey();
24+
Integer charValue = charMap.get(key) == null ? 0 : charMap.get(key);
25+
if (entry.getValue() > charValue) {
26+
return 0;
27+
}
28+
}
29+
return 1;
30+
}
31+
32+
private HashMap<Character, Integer> getCharCount(String chars) {
33+
HashMap<Character, Integer> map = new HashMap<>();
34+
for (char c : chars.toCharArray()) {
35+
if (map.get(c) != null) {
36+
map.put(c, map.get(c) + 1);
37+
} else {
38+
map.put(c, 1);
39+
}
40+
}
41+
return map;
42+
}
43+
44+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package hashmap;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.core.Is.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
/**
9+
* @author liangqian0723@gmail.com
10+
* @since 2020/3/17 11:08 PM
11+
*/
12+
public class LC_1160_FindWordsThatCanBeFormedByCharactersTest {
13+
@Test
14+
public void test_find_words_that_can_be_formed_by_characters() {
15+
LC_1160_FindWordsThatCanBeFormedByCharacters fc = new LC_1160_FindWordsThatCanBeFormedByCharacters();
16+
assertThat(fc.countCharacters(new String[]{"cat", "bt", "hat", "tree"}, "atach"), is(6));
17+
}
18+
}

0 commit comments

Comments
 (0)