Thinking process
- quick look up
- use hash set or hash map
Mistakes
- corner cases!!!
- [], isUnique("a")? => true
- ["a"], isUnique("")? => true
- [""], isUnique("a")? => true
["hello"], isUnique("hello")? => true
- because of this one, I should use hash map
public class ValidWordAbbr {
private Map<String, String> abbr;
public ValidWordAbbr(String[] dictionary) {
abbr = new HashMap<String, String>();
for (String word : dictionary) {
String s = getAbbr(word);
if (abbr.containsKey(s) && !abbr.get(s).equals(word)) {
abbr.put(s, "");
} else {
abbr.put(s, word);
}
}
}
public boolean isUnique(String word) {
if (abbr.isEmpty()) return true;
if (word.length() == 0) return true;
String s = getAbbr(word);
return !abbr.containsKey(s) || (abbr.containsKey(s) && abbr.get(s).equals(word));
}
private String getAbbr(String str) {
int len = str.length();
if (len <= 2) {
return str;
}
StringBuilder res = new StringBuilder();
res.append(str.charAt(0));
res.append(len - 2);
res.append(str.charAt(len - 1));
return res.toString();
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");