LeetCode 242. Valid Anagram (验证变位词)
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?
题目标签:Hash Table
题目给了我们两个string, 让我们判断它们是不是变位词。
方法1:可以利用HashMap 来记录string s 的字母,和数量,接着用t 的字母和数量 来验证。
方法2:可以把两个string 变为 char array,接着sort 两个array,比较它们是不是一致。
Java Solution 1:
Runtime beats 18.65%
完成日期:05/27/2017
关键词:HashMap
关键点:利用HashMap来存入s,用t 来验证
1 class Solution 2 { 3 public boolean isAnagram(String s, String t) 4 { 5 /* Solution 1: HashMap */ 6 HashMap<Character, Integer> map = new HashMap<>(); 7 8 // first time: store each s char and occurrence into map 9 for(int i=0; i<s.length(); i++) 10 { 11 char sChar = s.charAt(i); 12 map.put(sChar, map.getOrDefault(sChar, 0) + 1); 13 } 14 // second time: compare t char with map to see match or not 15 for(int i=0; i<t.length(); i++) 16 { 17 char tChar = t.charAt(i); 18 19 if(!map.containsKey(tChar)) 20 return false; 21 22 if(map.get(tChar) == 1) 23 map.remove(tChar); 24 else 25 map.put(tChar, map.get(tChar) - 1); 26 27 28 } 29 30 return map.size() == 0 ? true : false; 31 } 32 }
Java Solution 2:
Runtime beats 28.32%
完成日期:05/27/2017
关键词:Sort
关键点:把s 和t 都转化为char array,然后sort
1 class Solution 2 { 3 public boolean isAnagram(String s, String t) 4 { 5 /* Solution 2: sort */ 6 if(s.length() != t.length() || s == null || t == null) 7 return false; 8 9 10 char[] s_arr = s.toCharArray(); 11 12 Arrays.sort(s_arr); 13 14 char[] t_arr = t.toCharArray(); 15 16 Arrays.sort(t_arr); 17 18 for(int i=0; i<s.length(); i++) 19 { 20 if(s_arr[i] != t_arr[i]) 21 return false; 22 } 23 24 return true; 25 26 } 27 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List