码迷,mamicode.com
首页 > 其他好文 > 详细

242. Valid Anagram

时间:2018-10-11 15:44:25      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:col   car   sum   忘记   you   amp   val   记录   cas   

Given two strings s and , 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;
    }

 

242. Valid Anagram

标签:col   car   sum   忘记   you   amp   val   记录   cas   

原文地址:https://www.cnblogs.com/jessie2009/p/9772652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!