import java.util.*;

/**
 * Anagram will give you anagram info about a word
 */
public class Anagram {
  String word;
  Map<Character, Integer> map;
  
  public Anagram(String w) {
    this.word = w;
    this.map = generateCharMap(this.word);
  }

  public List<String> match(List<String> matchWords) {
    List<String> ret = new ArrayList<String>();
    Map<Character, Integer> myWordMap = this.generateCharMap(this.word);
    for(int i = 0; i < matchWords.size(); i++) {
      // Must have the same number of characters
      String tstWord = matchWords.get(i);
      if(tstWord.length() != this.word.length()) {
        continue;
      } 
    
      if(this.isAnagram(tstWord)) {
        ret.add(matchWords.get(i));
      }
    }
    return ret;
  }

  private boolean isAnagram(String tst) {
    Map<Character, Integer> tstMap = new HashMap<Character, Integer>(this.map);
    boolean ret = true;
    tst = tst.toLowerCase();
    if(tst.equals(this.word.toLowerCase())) {
      return false;
    }
    for(int i = 0; i < tst.toCharArray().length; i++) {
      if(tstMap.containsKey(tst.toCharArray()[i])) {
        int left = tstMap.get(tst.toCharArray()[i]);
        if(left <= 0) {
          ret = false;
        } else {
          left--;
          tstMap.put(tst.toCharArray()[i], left);
        }
      } else {
        ret = false;
      }
      if(!ret) {
        // If ret ever hits false, we're done.
        break;
      }
    }
    return ret;
  }

  private Map<Character, Integer> generateCharMap(String wrd) {
    Map<Character, Integer> wordMap = new HashMap<Character, Integer>();
    for(int i = 0; i < this.word.toCharArray().length; i++) {
      Character tst = this.word.toCharArray()[i];
      tst = Character.toLowerCase(tst);
      if(!wordMap.containsKey(tst)) {
        wordMap.put(tst, 0);
      }
      wordMap.put(tst, wordMap.get(tst)+1);
    }
    return wordMap;
  }
}
