标签:col car sum 忘记 you amp val 记录 cas
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?
如果是unicode, c - ‘a‘可能会变成负数,因为减a是为了让小写字母map到从0到25的index上,unicode可以用hashmap来记录
//Time: O(n), Space: O(n) public boolean isAnagram(String s, String t) { if (s.length() != t.length()) {//一定不要忘记开始先比较长度,eg:"ab", "a" return false; } int[] map = new int[26]; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); map[c - ‘a‘]++; } for (int i = 0; i < t.length(); i++) { char c = t.charAt(i); map[c - ‘a‘]--; if (map[c - ‘a‘] < 0) { return false; } } return true; }
标签:col car sum 忘记 you amp val 记录 cas
原文地址:https://www.cnblogs.com/jessie2009/p/9772652.html