Arrays & Hashing

Valid anagram

Estimated reading: 1 minute 36 views

Given two strings s and t, write a function that returns true if the two strings are anagrams of each other, otherwise returns false.

Definition:

An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.

Examples:

Example 1:

  • Input: s = "racecar", t = "carrace"
  • Output: true

Example 2:

  • Input: s = "jar", t = "jam"
  • Output: false

Constraints:

  • Both s and t consist of lowercase English letters.
				
					  public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

        int[] store = new int[26];

        for (int i = 0; i < s.length(); i++) {
            store[s.charAt(i) - 'a']++;
            store[t.charAt(i) - 'a']--;
        }

        for (int n : store) if (n != 0) return false;

        return true;
    }
				
			
Share this Doc

Valid anagram

Or copy link

CONTENTS