Leetcode[242] Valid Anagram
29 Nov 2015###Task1 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.
Note: You may assume the string contains only lowercase alphabets.
Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?
###Python
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
map = {}
for c in s:
if c in map:
map[c] += 1
else:
map[c] = 1
for c in t:
if c not in map:
return False
else:
map[c] -= 1
for c in map:
if map[c] != 0:
return False
return True
###Java
import java.util.*;
public class Solution {
public boolean isAnagram(String s, String t) {
if (s == null || t == null || s.length() != t.length()) {
return false;
}
if (s.length() == 0) {
return true;
}
char[] arrS = s.toCharArray();
char[] arrT = t.toCharArray();
Arrays.sort(arrT);
Arrays.sort(arrS);
return String.valueOf(arrT).equals(String.valueOf(arrS));
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.isAnagram("eat", "tea"));
}
}
####Array / map
import java.util.*;
public class Solution {
public boolean isAnagram(String s, String t) {
if (s == null || t == null || s.length() != t.length()) {
return false;
}
if (s.length() == 0) {
return true;
}
int[] charArr = new int[26];
for (int i = 0; i < s.length(); i++) {
charArr[s.charAt(i) - 'a']++;
charArr[t.charAt(i) - 'a']--;
}
for (int i = 0; i < charArr.length; i++) {
if (charArr[i] != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.isAnagram("eat", "tea"));
}
}
###Points
»> alist = [1, 3, 2]
»> alist.sort()
»> alist
[1, 2, 3]
»> alist.sorted()
Traceback (most recent call last):
File “
sort() is a method of list. As explained, it sorts the list in place
and it does not return the list as a reminder of that fact.
sorted() is a builtin function, not a method on list, because it's
more general taking any iterator as its first argument (for example an
open file), not just a list. It of course does return a list.
- so we use sorted(s) == sorted(t) to check cause s.sort() does not return anything at all!