Utopi
a

有效的字母异位词

Map is fast !

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

Example

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

我的(4 ms)

public boolean isAnagram(String s, String t) { if (s.length()!=t.length()){ return false; } char a[] = s.toCharArray(); char b[] = t.toCharArray(); Arrays.sort(a); Arrays.sort(b); if (Arrays.equals(a, b)){ return true; } return false; }

先把字符串转化为字符数组,然后对字符数组进行排序,最后比较。

2ms

class Solution { public boolean isAnagram(String s, String t) { if(s == null || t == null || s.length() != t.length()) return false; int[] map = new int[26]; for(char c : s.toCharArray()){ map[c-'a']++; } for(char c : t.toCharArray()){ map[c-'a']--; } for(int i = 0;i<26;i++){ if(map[i]!= 0) return false; } return true; } }