|
| 1 | +package io.github.dunwu.algorithm.string; |
| 2 | + |
| 3 | + |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +/* |
| 8 | +@see https://leetcode.com/problems/valid-anagram/ |
| 9 | +
|
| 10 | +Given two strings s and t , write a function to determine if t is an anagram of s. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +
|
| 14 | +Input: s = "anagram", t = "nagaram" |
| 15 | +Output: true |
| 16 | +Example 2: |
| 17 | +
|
| 18 | +Input: s = "rat", t = "car" |
| 19 | +Output: false |
| 20 | +Note: |
| 21 | +You may assume the string contains only lowercase alphabets. |
| 22 | +
|
| 23 | +Follow up: |
| 24 | +What if the inputs contain unicode characters? How would you adapt your solution to such case? |
| 25 | +*/ |
| 26 | +public class ValidAnagram { |
| 27 | + public static boolean isAnagram(String s, String t) { |
| 28 | + if (s == null && t == null) return true; |
| 29 | + else if (s == null || t == null) return false; |
| 30 | + else if (s.length() != t.length()) return false; |
| 31 | + |
| 32 | + Map<Character, Integer> map = new HashMap<Character, Integer>(); |
| 33 | + for (int i = 0; i < s.length(); i++) { |
| 34 | + if (map.containsKey(s.charAt(i))) { |
| 35 | + Integer count = map.get(s.charAt(i)); |
| 36 | + ++count; |
| 37 | + map.remove(s.charAt(i)); |
| 38 | + map.put(s.charAt(i), count); |
| 39 | + } else { |
| 40 | + map.put(s.charAt(i), 1); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + Map<Character, Integer> map2 = new HashMap<Character, Integer>(); |
| 45 | + for (int j = 0; j < t.length(); j++) { |
| 46 | + if (map2.containsKey(t.charAt(j))) { |
| 47 | + Integer count = map2.get(t.charAt(j)); |
| 48 | + ++count; |
| 49 | + map2.remove(t.charAt(j)); |
| 50 | + map2.put(t.charAt(j), count); |
| 51 | + } else { |
| 52 | + map2.put(t.charAt(j), 1); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if (map.size() != map2.size()) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + for (Map.Entry<Character, Integer> entry1 : map.entrySet()) { |
| 61 | + Integer m1value = entry1.getValue() == null ? 0 : entry1.getValue(); |
| 62 | + Integer m2value = map2.get(entry1.getKey()) == null ? 0 : map2.get(entry1.getKey()); |
| 63 | + if (!m1value.equals(m2value)) { |
| 64 | + return false; |
| 65 | + } |
| 66 | + } |
| 67 | + return true; |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] args) { |
| 71 | + boolean result1 = isAnagram("anagram", "nagaram"); |
| 72 | + boolean result2 = isAnagram("rat", "car"); |
| 73 | + boolean result3 = isAnagram("a", "ab"); |
| 74 | + System.out.println("result:" + result1); |
| 75 | + System.out.println("result:" + result2); |
| 76 | + System.out.println("result:" + result3); |
| 77 | + } |
| 78 | +} |
0 commit comments