1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 1704. Determine if String Halves Are Alike

Posted at

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;
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?