首页 > 其他 > 详细

242. Valid Anagram

时间:2018-10-11 15:39:46      阅读:149      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!