
Sort, Easy
Question
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
1 2
|
Input: s = "anagram", t = "nagaram" Output: true
|
Example 2:
1 2
|
Input: s = "rat", t = "car" Output: 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?
Answer
1 2 3 4 5 6 7 8 9
|
class { public boolean isAnagram(String s, String t) { char ss[] = s.toCharArray(); char tt[] = t.toCharArray(); Arrays.sort(ss); Arrays.sort(tt); return Arrays.equals(ss,tt); } }
|
Running time: depends on the sort algorithm, O(nlogn)
Space: O(n), n the length of String
Better Answer
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class { public boolean isAnagram(String s, String t) { int chAlp[] = new int[26]; for(int i=0;i<s.length();i++) chAlp[s.charAt(i)-'a']++; for(int i=0;i<t.length();i++) chAlp[t.charAt(i)-'a']--; for(int temp:chAlp) if(temp!=0) return false; return true; } }
|
近期评论