242. Valid Anagram
242. Valid Anagram
class Solution { public boolean isAnagram(String s, String t) { int[] map = new int[26]; for(int i = 0; i < s.length(); i++){ map[s.charAt(i) - 'a']++; } for(int i = 0; i < t.length(); i++){ map[t.charAt(i) - 'a']--; } for(int i = 0; i < 26; i++){ if(map[i] != 0) return false; } return true; } }
class Solution { public boolean isAnagram(String s, String t) { // map char to hashmap for s // check the freq in t if(s.length() != t.length()){ return false; } HashMap<Character, Integer> map = new HashMap<>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); Integer freq = map.get(c); if(freq == null){ map.put(c, 1); }else{ map.put(c, freq + 1); } } int count = 0; // if count == map.size(), then its an anagram // count ++ when one freq is 0 for(int i = 0; i < t.length(); i++){ char c = t.charAt(i); Integer freq = map.get(c); if(freq == null){ return false; }else{ map.put(c, freq - 1); if(freq == 1) count++; } } return count == map.size(); } }
public class Solution { public boolean isAnagram(String s, String t) { int[] alphabet = new int[26]; for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++; for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--; for (int i : alphabet) if (i != 0) return false; return true; } }
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 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?
posted on 2018-08-09 17:32 猪猪🐷 阅读(83) 评论(0) 收藏 举报
浙公网安备 33010602011771号