Two Strings Are Anagrams

LintCode-158.Two Strings Are Anagrams

Write a method anagram(s,t) to decide if two strings are anagrams or not.

Clarification: What is Anagram?

  • Two strings are anagram if they can be the same after change the order of characters.

Example: Given s = "abcd", t = "dcab", return true. Given s = "ab", t = "ab", return true. Given s = "ab", t = "ac", return false.

Challenge: O(n) time, O(1) extra space

public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        if (s == null || t == null) {
            return false;
        }
        
        if (s.length() != t.length()) {
            return false;
        }
        
        int[] charCount = new int[256];
        for (int i = 0; i < s.length(); i++) {
            charCount[s.charAt(i)]++;
        }
        
        for (int i = 0; i < t.length(); i++) {
            charCount[t.charAt(i)]--;
            
            if (charCount[t.charAt(i)] < 0) {
                return false;
            }
        }

        return true;
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge