242. Valid-Anagram

difficulty: Easy

section pre{ background-color: #eee; border: 1px solid #ddd; padding:10px; border-radius: 5px; }

Given two strings s and t , 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?

Method One

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] map = new int[26];
        for(char c : s.toCharArray()) {
            map[ c - 'a' ]++;
        }
        for(char c : t.toCharArray()) {
            map[ c - 'a' ]--;
        }
        for(int n : map) {
            if(n != 0) {
                return false;
            }
        }
        return true;
    }
}

Last updated

Was this helpful?