标签:
题目:
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?
链接: http://leetcode.com/problems/valid-anagram/
题解:
验证Anagram。这道题目有不少解决方法。
最简单的是排序以后对比数组。
Time Complexity - O(nlogn), Space Complexity - O(n)
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[] sArr = s.toCharArray(); char[] tArr = t.toCharArray(); Arrays.sort(sArr); Arrays.sort(tArr); return Arrays.equals(sArr, tArr); } }
我们也可以使用HashMap, 遍历s把其中的元素保存到map中,再遍历t检查是否具有和s完全相同的元素及数量。
Time Complexity - O(n), Space Complexity - O(1)。 但实际运行时速度反而比较慢。
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; Map<Character, Integer> map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(map.containsKey(c)) map.put(c, map.get(c) + 1); else map.put(c, 1); } for(int i = 0; i < t.length(); i++) { char c = t.charAt(i); if(!map.containsKey(c)) return false; else { if(map.get(c) == 0) return false; map.put(c, map.get(c) - 1); } } return true; } }
也可以用bitMap,因为题目说明只含有小写字母,所以我们可以建立一个length为26的bitmap,同时遍历s和t, 递增bitmap[char s - ‘a‘], 递减bitmap[char t - ‘a‘],最后检查是否每一位都为0,是则返回true, 否则返回false。
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[] bitMap = new int[26]; for(int i = 0; i < s.length(); i++) { bitMap[s.charAt(i) - ‘a‘]++; bitMap[t.charAt(i) - ‘a‘]--; } for(int i : bitMap) if(i != 0) return false; return true; } }
Reference:
https://leetcode.com/discuss/57903/java-solution-using-sort
https://leetcode.com/discuss/49399/accepted-java-o-n-solution-in-5-lines
https://leetcode.com/discuss/61456/my-java-solution-8ms
https://leetcode.com/discuss/49795/share-my-java-solution
https://leetcode.com/discuss/50631/jave-simple-and-efficient-solution
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5006201.html