数两个string的各个字母个数,然后比较两个计数的数组每一位是否一样
public class Solution {
public boolean isAnagram(String s, String t) {
int [] sArr = new int [26];
int [] tArr = new int [26];
if (s.length() != t.length() )
return false;
for ( int i = 0; i < s.length(); i ++){
char c = s.charAt(i);
int pos = c - 'a';
sArr[ pos ] ++;
char c2 = t.charAt(i);
int pos2 = c2 - 'a';
tArr[ pos2 ] ++;
}
for (int i = 0; i < 26; i ++){
if ( sArr[i] != tArr[i])
return false;
}
return true;
}
}
简便做法是 只用一个array 第一个s里面的char ++ 第二个t里面的--
public class Solution {
public boolean isAnagram(String s, String t) {
int [] counts = new int [ 26 ];
if ( s.length() != t.length () )
return false;
for ( int i = 0; i < s.length(); i ++ ){
counts [ s.charAt( i ) - 'a' ] ++;
counts [ t.charAt( i ) - 'a' ] -- ;
}
for ( int i = 0; i < 26; i ++ ){
if ( counts[ i ] != 0 )
return false;
}
return true;
}
}