LeetCode刷题Easy篇.Valid Anagram

题目

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?

十分钟尝试

利用hashmap存储字符串s,然后遍历字符串t,放入map,存在,则把次数减去1,不存在则val是1,如果字符串完全是相同的字符组成,最后map中的元素都为0.如果有不等于0的,返回false。另外,数组也可以代替map,因为查询也是O(1)

代码如下,我们用map实现,如果用数组,为了从字符到索引,可以同时减去‘A’,这样相同元素就有相同的索引:

class Solution {
    public boolean isAnagram(String s, String t) {
        Map<Character,Integer> map=new HashMap();
        for(int i=0;i<s.length();i++){
            Character curr=s.charAt(i);
            map.put(curr,map.getOrDefault(curr,0)+1);
        }
        for(int i=0;i<t.length();i++){
             Character curr=t.charAt(i);
             map.put(curr,map.getOrDefault(curr,0)-1);
        }
        for(Map.Entry entry : map.entrySet()){
            if((Integer)entry.getValue()!=0) return false;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85004316