Advertisement
1988coder

242. Valid Anagram

Jan 6th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/valid-anagram/
  3. import java.util.HashMap;
  4.  
  5. /**
  6.  * Time Complexity: O(N)
  7.  *
  8.  * Space Complexity: O(N)
  9.  *
  10.  * N = Length of input string S or T.
  11.  */
  12. class Solution {
  13.     public boolean isAnagram(String s, String t) {
  14.         if (s == null || t == null || s.length() != t.length()) {
  15.             return false;
  16.         }
  17.         if (s.length() == 0) {
  18.             return true;
  19.         }
  20.  
  21.         HashMap<Character, Integer> map = new HashMap<>();
  22.         for (int i = 0; i < s.length(); i++) {
  23.             map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
  24.             map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0) - 1);
  25.         }
  26.  
  27.         for (char key : map.keySet()) {
  28.             if (map.get(key) != 0) {
  29.                 return false;
  30.             }
  31.         }
  32.  
  33.         return true;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement