leetcode 242 有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
//v1.0 使用排序class Solution {public boolean isAnagram(String s, String t) {char[] sChar = s.toCharArray();char[] tChar = t.toCharArray();Arrays.sort(sChar);Arrays.sort(tChar);return Arrays.equals(sChar,tChar);}}//v2.0 标签:哈希映射//首先判断两个字符串长度是否相等,不相等则直接返回 false//若相等,则初始化 26 个字母哈希表,遍历字符串 s 和 t//s 负责在对应位置增加,t 负责在对应位置减少//如果哈希表的值都为 0,则二者是字母异位词class Solution {public boolean isAnagram(String s, String t) {if(s.length() != t.length()) return false;int[] alphabet = new int[26];for(int i = 0;i<s.length();i++){alphabet[s.charAt(i)-'a']++;alphabet[t.charAt(i)-'a']--;}for(int j = 0;j<26;j++){if(alphabet[j]!=0) return false;}return true;}}
leetcode 1207 独一无二的出现次数
给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。
如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false。
//v1.0class Solution {public boolean uniqueOccurrences(int[] arr) {Map<Integer,Integer> map = new HashMap<Integer,Integer>();int[] nums = new int[2001];for(int i=0;i<arr.length;i++){nums[arr[i]+1000]++;}for(int j=0;j<2001;j++){if(nums[j]==0) continue;if(map.containsKey(nums[j])){return false;}map.put(nums[j],j);}return true;}}//v2.0class Solution {public boolean uniqueOccurrences(int[] arr) {HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();for(int elem : arr){map.put(elem,map.getOrDefault(elem,0)+1);}return map.size() == new HashSet<Integer>(map.values()).size();}}
