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?
第一次用了hashmap理论上来讲时间的效率应该是O(n)的但是代码写得不太简洁,最后导致了时间效率比较低,以及频繁的使用charAt(i)这个方法所耗费的时间是很多的

public class Solution {
    public boolean isAnagram(String s, String t) {
       HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i = 0 ; i < s.length() ; i++)
        {
            if(map.containsKey(s.charAt(i)))
                map.put(new Character(s.charAt(i)), new Integer(map.get(s.charAt(i))+1));
            else
                map.put(new Character(s.charAt(i)), new Integer(1));
        }

        for(int i = 0 ; i < t.length() ; i++ )
        {
            if(map.containsKey(t.charAt(i))==false)
                return false;
            if(map.containsKey(t.charAt(i))&&map.get(t.charAt(i))==1)
                map.remove(t.charAt(i));
            else if(map.containsKey(t.charAt(i))&&map.get(t.charAt(i))>1)
                map.put(new Character(t.charAt(i)), new Integer(map.get(t.charAt(i))-1));
        }
    if(map.size()==0)
        return true;
        return false;
    }
}

但是大体的想法,思路都是对的,于是就在讨论区拿着大神写的精简的代码试了一下,发现用时是40ms

public class Solution {
   public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        Map<Character, Integer> m = new HashMap<>();
        for (Character c : s.toCharArray()) {
            int count = m.containsKey(c) ? m.get(c) : 0;
            m.put(c, ++count);
        }
        for (Character c : t.toCharArray()) {
            int count = m.containsKey(c) ? m.get(c) : 0;
            if (count - 1 == 0) {
                m.remove(c);
            } else {
                m.put(c, --count);
            }
        }
        return m.size() == 0;
    }
}

后来又发现使用排序的方法,把字符串排序过后使用equals方法来比较两个字符串是否一样来解决,系统内部的排序是基于比较的排序所以排序的效率理论上来讲应该是O(nlogn)的,但是在这道题中最后测试的结果为使用排序要比使用散列的效果好结果为8ms

public class Solution {
 public boolean isAnagram(String s, String t) {
    if(t.length() != s.length())
        return false;
    if(t.length() == 0 && s.length() == 0)
        return true;
    char[] cs = s.toCharArray();
    char[] ts = t.toCharArray();
    Arrays.sort(cs);
    Arrays.sort(ts);
    for(int i = 0; i < cs.length; i++)
    {
        if(cs[i] != ts[i])
            return false;
    }
    return true;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值