Description
Write a methodanagram(s,t)
to decide if two strings are anagrams or not.
Have you met this question in a real interview?
Yes
Clarification
What isAnagram?
- Two strings are anagram if they can be the same after change the order of characters.
Example
Given s ="abcd"
, t ="dcab"
, returntrue
.
Given s ="ab"
, t ="ab"
, returntrue
.
Given s ="ab"
, t ="ac"
, returnfalse
.
Solution
按ASCII码的个数256来开辟数组。
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
// write your code here
if (s == null && t == null) {
return true;
}
if (s == null || t == null || s.length() != t.length()) {
return false;
}
int[] count = new int[256];
for (char c : s.toCharArray()) {
count[(int)c]++;
}
for (char c : t.toCharArray()) {
count[(int)c]--;
if (count[(int)c] < 0) {
return false;
}
}
return true;
}
};