My code:
public class ValidWordAbbr {
HashMap<String, HashSet<String>> tracker = new HashMap<String, HashSet<String>>();
public ValidWordAbbr(String[] dictionary) {
if (dictionary == null || dictionary.length == 0)
return;
for (int i = 0; i < dictionary.length; i++) {
String key = trans(dictionary[i]);
if (tracker.containsKey(key)) {
HashSet<String> hs = tracker.get(key);
hs.add(dictionary[i]);
}
else {
HashSet<String> hs = new HashSet<String>();
hs.add(dictionary[i]);
tracker.put(key, hs);
}
}
}
public boolean isUnique(String word) {
String key = trans(word);
if (!tracker.containsKey(key))
return true;
else {
HashSet<String> hs = tracker.get(key);
if (hs.size() <= 1 && hs.contains(word))
return true;
else
return false;
}
}
public String trans(String s) {
if ( s == null || s.length() <= 2)
return s;
return "" + s.charAt(0) + (s.length() - 2) + s.charAt(s.length() - 1);
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");
一開始想復雜了。。
今晚很累。不多說了。
Anyway, Good luck, Richardo!
My code:
public class ValidWordAbbr {
HashMap<String, String> dic = new HashMap<String, String>();
public ValidWordAbbr(String[] dictionary) {
if (dictionary == null || dictionary.length == 0) {
return;
}
for (String curr : dictionary) {
String key = extractKey(curr);
if (dic.containsKey(key)) {
if (!dic.get(key).equals(curr)) {
dic.put(key, "");
}
}
else {
dic.put(key, curr);
}
}
}
public boolean isUnique(String word) {
String key = extractKey(word);
return !dic.containsKey(key) || dic.get(key).equals(word);
}
private String extractKey(String s) {
if (s == null || s.length() <= 2) {
return s;
}
StringBuilder ret = new StringBuilder();
ret.append(s.charAt(0));
ret.append("" + (s.length() - 2));
ret.append(s.charAt(s.length() - 1));
return ret.toString();
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");
這道題目有點意思。我的題意有理解錯了。后來看的答案。
reference:
https://discuss.leetcode.com/topic/30533/java-solution-with-one-hashmap-string-string-beats-90-of-submissions
他的意思是:
如果dic 不包含當前輸入string的abbreviation 或者 當前string與dic中
代表該abbreviation的string是一樣時,返回true
總結下 hashmap, hashset, hashtable
hashmap vs hashtable
hashmap supports null key and value
hashtable does not suppot null key or value
hashmap is not sychronized, we should use CurrentHashMap if we want
hashtable is synchronized
hashset can also add null element
hashset extends hashmap
when hashset adds element:
private final Object newObject = new Object();
public boolean add(K k) {
return map.put(k, newObject) == null ? false : true;
}
hashmap put null key into bucket 0
Anyway, Good luck, Richardo! -- 09/02/2016