0%

Leetcode242-validAnagram

Description

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

Example

Example 1:

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

Example 2:
1
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?

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isAnagram(String s, String t) {
if (s == null && t == null) return false;
if (s.length() != t.length()) return false;
int[] count = new int[26];
for (int i = 0; i < s.length(); i++){
count[s.charAt(i) - 'a'] ++;
count[t.charAt(i) - 'a'] --;
}
for (int num : count)
if (num != 0) return false;
return true;
}
}