1704. Determine if String Halves Are Alike
難易度
Easy
アプローチ
Hashmap
class Solution {
public boolean halvesAreAlike(String s) {
String s1 = s.substring(0, s.length() / 2);
String s2 = s.substring(s.length() / 2);
HashMap<Character, Integer> h1 = new HashMap<>();
HashMap<Character, Integer> h2 = new HashMap<>();
h1.put('a', 0);
h1.put('e', 0);
h1.put('i', 0);
h1.put('o', 0);
h1.put('u', 0);
h1.put('A', 0);
h1.put('E', 0);
h1.put('I', 0);
h1.put('O', 0);
h1.put('U', 0);
for (char c1 : s1.toCharArray()) {
if (h1.containsKey(c1)) {
h1.put(c1, h1.get(c1) + 1);
}
}
h2.put('a', 0);
h2.put('e', 0);
h2.put('i', 0);
h2.put('o', 0);
h2.put('u', 0);
h2.put('A', 0);
h2.put('E', 0);
h2.put('I', 0);
h2.put('O', 0);
h2.put('U', 0);
for (char c2 : s2.toCharArray()) {
if (h2.containsKey(c2)) {
h2.put(c2, h2.get(c2) + 1);
}
}
int sum1 = h1.values().stream().mapToInt(integer -> integer).sum();
int sum2 = h2.values().stream().mapToInt(integer -> integer).sum();
return sum1 == sum2;
}
}