Leetcode804 Unique Morse Code Words Java实现

 最近开启了java的刷题之路,于是打开leetcode/tag/string 挑了AC率最高的一题,战绩还不错。没什么特殊的技巧,就mark一下。java水平还是菜,不翻文档寸步难行…多刷题吧!

class Solution {
    public int uniqueMorseRepresentations(String[] words) {
        String[] morseCodes = new String[] {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        Set<String> resultMorseCodes = new HashSet<>();        //store the result morse codes and remove the duplicated one
        for(String word:words) {
            String resultCode = "";
            for(char letter:word.toCharArray()) {
                resultCode+=morseCodes[letter-'a'];
            }
            resultMorseCodes.add(resultCode);
        }
        return resultMorseCodes.size();
    }
}

 还有可以提高的点嘛?发现自己用了string的+也就是append方法,换成StringBuilder可能会更快,于是试了下:

class U804v2{
    public int uniqueMorseRepresentations(String[] words) {
        String[] morseCodes = new String[] {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        Set<String> resultMorseCodes = new HashSet<>();        //store the result morse codes and remove the duplicated one
        for(String word:words) {
            StringBuilder resultCode = new StringBuilder();
            for(char letter:word.toCharArray()) {
                resultCode.append(morseCodes[letter-'a']);
            }
            String resultCodeS = resultCode.toString();
            resultMorseCodes.add(resultCodeS);
        }
        return resultMorseCodes.size();        
    }
}

这次runtime变成了5ms。时间提升,时间复杂度没变,空间上使用了一个String数组存对照关系,一个HashSet寸结果,不再深究了。

第一道AC就这样吧~

猜你喜欢

转载自www.cnblogs.com/chason95/p/9269337.html