File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -45,3 +45,34 @@ public class ValidWordAbbr {
45
45
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
46
46
// vwa.isUnique("Word");
47
47
// vwa.isUnique("anotherWord");
48
+
49
+
50
+ // Shorter solution for ref (https://discuss.leetcode.com/topic/30533/java-solution-with-one-hashmap-string-string-beats-90-of-submissions/2)
51
+ public class ValidWordAbbr {
52
+ HashMap<String, String> map;
53
+ public ValidWordAbbr(String[] dictionary) {
54
+ map = new HashMap<String, String>();
55
+ for(String str:dictionary){
56
+ String key = getKey(str);
57
+ // If there is more than one string belong to the same key
58
+ // then the key will be invalid, we set the value to ""
59
+ if(map.containsKey(key)){
60
+ if(!map.get(key).equals(str)){
61
+ map.put(key, "");
62
+ }
63
+ }
64
+ else{
65
+ map.put(key, str);
66
+ }
67
+ }
68
+ }
69
+
70
+ public boolean isUnique(String word) {
71
+ return !map.containsKey(getKey(word))||map.get(getKey(word)).equals(word);
72
+ }
73
+
74
+ String getKey(String str){
75
+ if(str.length()<=2) return str;
76
+ return str.charAt(0)+Integer.toString(str.length()-2)+str.charAt(str.length()-1);
77
+ }
78
+ }
You can’t perform that action at this time.
0 commit comments