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
题意:
验证变位词
何谓anagram?
思路:
用int[] map = new int[256]代表一个简化版的HashMap
挨个扫字符串s的每个字符,在map里标注++
挨个扫字符串t的每个字符,在map里标注--
根据valid anagram属性, map里最终应该都该为0。
代码:
1 class Solution { 2 public boolean isAnagram(String s, String t) { 3 if(s.length() != t.length()) return false; 4 int[] map = new int[256]; 5 for(int i = 0 ; i < s.length(); i++){ 6 map[s.charAt(i)]++; 7 map[t.charAt(i)]--; 8 } 9 for(int i : map){ 10 if(i != 0){ 11 return false; 12 } 13 } 14 return true; 15 } 16 }