Skip to content

Latest commit

 

History

History
executable file
·
59 lines (51 loc) · 1.35 KB

242. Valid Anagram.md

File metadata and controls

executable file
·
59 lines (51 loc) · 1.35 KB

242. Valid Anagram

Question

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

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

Example 2:

Input: s = "rat", t = "car"
Output: false

Thinking:

  • Method 1:类似使用MAP来存储出现次数
class Solution {
    public boolean isAnagram(String s, String t) {
        int[] count = new int[26];
        int sLen = s.length();
        int tLen = t.length();
        if(sLen != tLen) return false;
        for(int i = 0; i < sLen; i++)
            count[s.charAt(i) - 'a']++;
        for(int i = 0; i < tLen; i++)
            count[t.charAt(i) - 'a']--;
        for(int i = 0; i < 26; i++)
            if(count[i] != 0) return false;
        return true;
    }
}

Second time

  1. Since it mentions that only unicode will be included, so I used a array as a map.
class Solution {
    public boolean isAnagram(String s, String t) {
        int[] count = new int[256];
        char[] sArr = s.toCharArray();
        for(int i = 0; i < sArr.length; i++){
            count[sArr[i]]++;
        }
        char[] tArr = t.toCharArray();
        for(int i = 0; i < tArr.length; i++){
            count[tArr[i]]--;
        }
        for(int i = 0; i < 256; i++){
            if(count[i] != 0) return false;
        }
        return true;
    }
}