DEV Community

shine
shine

Posted on

[📝LeetCode #242] Valid Anagram

🎀 The Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example:

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

👩‍💻 My Answer

class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; HashMap map = new HashMap(); char counter = 0; int scount = 0, tcount = 0; while (counter < s.length()) { char letter = s.charAt(counter); if (!map.containsKey(letter)) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == letter) scount++; if (t.charAt(i) == letter) tcount++; } } if (scount != tcount) return false; else map.put(letter, scount); counter++; } return true; } } 
Enter fullscreen mode Exit fullscreen mode

Runtime & Memory

Pro & Con

  • ✖️ Runtime & Memory

💋 Ideal Answer

Approach - "Array"

I watched the YouTube video and found that it's faster if I use int instead of a HashMap. Here is my array method.

New Code

class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; int[] scount = new int[26]; int[] tcount = new int[26]; for (int i = 0; i < s.length(); i++) { scount[s.charAt(i)-'a']++; tcount[t.charAt(i)-'a']++; } for (int i = 0; i < 26; i++) { if (scount[i] != tcount[i]) return false; } return true; } } 
Enter fullscreen mode Exit fullscreen mode

Runtime & Memory

This beats only 57%, so I was wondering what the ideal answer is. Then, I found the faster answer in LeetCode problem.

public class Solution { public boolean isAnagram(String s, String t) { int[] alphabet = new int[26]; for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++; for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--; for (int i : alphabet) if (i != 0) return false; return true; } } 
Enter fullscreen mode Exit fullscreen mode

New Runtime & Memory

💡 What I Learned

  • Use array instead of HashMap to make it faster.
    int[] alphabet = new int[26];

  • I used to use two arrays for s and t. But use ONE instead.
    If you find the letter in s, increment;t while the letter in t decreases the count in the array.

Top comments (0)