242. Valid Anagram
Easy
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?
package leetcode.easy; public class ValidAnagram { public boolean isAnagram1(String s, String t) { if (s.length() != t.length()) { return false; } char[] str1 = s.toCharArray(); char[] str2 = t.toCharArray(); java.util.Arrays.sort(str1); java.util.Arrays.sort(str2); return java.util.Arrays.equals(str1, str2); } public boolean isAnagram21(String s, String t) { if (s.length() != t.length()) { return false; } int[] counter = new int[26]; for (int i = 0; i < s.length(); i++) { counter[s.charAt(i) - 'a']++; counter[t.charAt(i) - 'a']--; } for (int count : counter) { if (count != 0) { return false; } } return true; } public boolean isAnagram22(String s, String t) { if (s.length() != t.length()) { return false; } int[] table = new int[26]; for (int i = 0; i < s.length(); i++) { table[s.charAt(i) - 'a']++; } for (int i = 0; i < t.length(); i++) { table[t.charAt(i) - 'a']--; if (table[t.charAt(i) - 'a'] < 0) { return false; } } return true; } @org.junit.Test public void test() { String s1 = "anagram"; String t1 = "nagaram"; String s2 = "rat"; String t2 = "car"; System.out.println(isAnagram1(s1, t1)); System.out.println(isAnagram1(s2, t2)); System.out.println(isAnagram21(s1, t1)); System.out.println(isAnagram21(s2, t2)); System.out.println(isAnagram22(s1, t1)); System.out.println(isAnagram22(s2, t2)); } }