Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
public class Solution {
public boolean isAnagram(String s, String t) {
if (s == null && t == null) {
return true;
}
if (s == null || t == null) {
return false;
}
char cs[] = s.toCharArray();
char ct[] = t.toCharArray();
Arrays.sort(cs);
Arrays.sort(ct);
String s2 = new String(cs);
String t2 = new String(ct);
return s2.equals(t2);
}
}
========
public class Solution {
public boolean isAnagram(String s, String t) {
if (s == null && t== null)
return true;
if (s == null || t== null || s.length() != t.length()) {
return false;
}
int[] arr = new int[256];
for (int i = 0; i < s.length();i++) {
arr[s.charAt(i)]++;
}
for (int i = 0; i < t.length(); i++) {
arr[t.charAt(i)]--;
if (arr[t.charAt(i)] < 0) {
return false;
}
}
return true;
}
}
没有评论:
发表评论