您的位置:首页 > 产品设计 > UI/UE

*LeetCode-Unique Word Abbreviation

2015-10-17 09:03 447 查看
这个题也很简单 但是要想全可能存在的情况 所以假如只有hello 那hello是可以的 或者根本dict里面没有这个词 也没有这个词的abb也是可以的

我用了map of string and int 来count有几个这样的abb 还用了一个set来记录dict里面的词 这样很浪费

简便方法是用abb做key 但是value就用dict里面的词本身 假如第二次碰到这个abb了 那么把value设置成“” 空 最后就判断哪个word和value是否相等就知道是否只有一个了 不相等就是并不是只有一个

public class ValidWordAbbr {
HashMap<String, Integer> map = new HashMap<String, Integer>();
Set<String> words = new HashSet<String>();
public ValidWordAbbr(String[] dictionary) {
for ( int i = 0; i < dictionary.length; i ++ ){
String abb = "";
int len = dictionary[ i ].length();
if ( len <= 2 )
abb = dictionary[ i ];
else
abb = dictionary[ i ].charAt( 0 ) + Integer.toString(len - 2) + dictionary[ i ].charAt( len - 1 );
if ( map.containsKey( abb ) )
map.put ( abb, 2 );
else
map.put ( abb, 1 );
words.add ( dictionary[ i ] );
}
}

public boolean isUnique(String word) {
String abb = "";
int len = word.length();
if ( len <= 2 )
abb = word;
else
abb = word.charAt( 0 ) + Integer.toString(len - 2) + word.charAt( len - 1 );
if ( !map.containsKey ( abb ) )
return true;
else if ( words.contains ( word ) && map.get( abb ) == 1 )
return true;
return false;
}
}

public class ValidWordAbbr {
HashMap<String, String> map = new HashMap<String, String>();
public ValidWordAbbr(String[] dictionary) {
for ( int i = 0; i < dictionary.length; i ++ ){
String abb = "";
int len = dictionary[ i ].length();
if ( len <= 2 )
abb = dictionary[ i ];
else
abb = dictionary[ i ].charAt( 0 ) + Integer.toString(len - 2) + dictionary[ i ].charAt( len - 1 );
if ( map.containsKey( abb ) )
map.put ( abb, "" );
else
map.put ( abb, dictionary[ i ] );
}
}

public boolean isUnique(String word) {
String abb = "";
int len = word.length();
if ( len <= 2 )
abb = word;
else
abb = word.charAt( 0 ) + Integer.toString(len - 2) + word.charAt( len - 1 );
if ( !map.containsKey ( abb ) )
return true;
if ( map.get( abb ).equals ( word ))
return true;
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: