242. Valid Anagram (Easy)

https://leetcode.com/problems/valid-anagram/

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

Solutions

class Solution {

    // Calculate the char frequency for each str, then compare if identical.

    public boolean isAnagram(String s, String t) {
        if (s == null && t == null) {
            return true;
        }

        if (s == null) {
            return false;
        }

        if (t == null) {
            return false;
        }

        if (s.length() != t.length()) {
            return false;
        }

        Map<Character, Integer> countMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if (!countMap.containsKey(c)) {
                countMap.put(c, 0);
            }

            countMap.put(c, countMap.get(c) + 1);
        }

        for (int i = 0; i < t.length(); i++) {
            Character c = t.charAt(i);
            if (!countMap.containsKey(c)) {
                return false;
            }

            countMap.put(c, countMap.get(c) - 1);
            if (countMap.get(c) < 0) {
                return false;
            }
        }

        return true;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-03-21 17:10:51

results matching ""

    No results matching ""