1. 程式人生 > >LeetCode刷題Easy篇.Valid Anagram

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;
    }
}