158.Two Strings Are Anagrams

1.Description(Easy)

Write a methodanagram(s,t)to decide if two strings are anagrams or not.

Clarification

What is Anagram?

  • Two strings are anagram if they can be the same after change the order of characters.

Example

Given s ="abcd", t ="dcab", returntrue. Given s ="ab", t ="ab", returntrue. Given s ="ab", t ="ac", returnfalse.

Challenge

O(n) time, O(1) extra space

Tags

Cracking The Coding Interview String

2.Code

用HashMap解决

public boolean anagram(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        HashMap<Character,Integer> map=new HashMap<>();
        for(int i=0;i<s.length();i++){
            char current=s.charAt(i);
            if(map.containsKey(current)){
                map.put(current, map.get(current)+1);
            }else{
                map.put(current,1);
            }
        }

        for(int i=0;i<t.length();i++){
            char current=t.charAt(i);
            if(map.containsKey(current)){
                map.put(current, map.get(current)-1);
            }else{
                return false;
            }
        }

        for(Character element :map.keySet()){
            if(map.get(element)!=0){
                return false;
            }
        }
        return true;
    }

Last updated