> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/amazon-mock-interview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/amazon-mock-interview/onsite-ii/158two-strings-are-anagrams.md).

# 158.Two Strings Are Anagrams

## 1.Description(Easy)

Write a method`anagram(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"`, return`true`.\
Given s =`"ab"`, t =`"ab"`, return`true`.\
Given s =`"ab"`, t =`"ac"`, return`false`.

[**Challenge**](https://www.lintcode.com/en/problem/two-strings-are-anagrams/#challenge)

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

[**Tags**](https://www.lintcode.com/en/problem/two-strings-are-anagrams/#tags)

[Cracking The Coding Interview](https://www.lintcode.com/tag/cracking-the-coding-interview/) [String](https://www.lintcode.com/tag/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;
    }
```
