>>문제설명

leetcode.com/problems/short-encoding-of-words/

 

Short Encoding of Words - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

> First Commit

import java.util.HashSet;

class Solution {
    public int minimumLengthEncoding(String[] words) {
        HashSet<String> indices = new HashSet<>();
        indices.add("");
        int answer = 0;
        for(String word : words){
            boolean check = false;
            for(String str : indices){
                if(str.endsWith(word)){
                    check = true;
                    break;
                }
                if(word.endsWith(str)){
                    check = true;
                    answer -= str.length() + 1;
                    indices.remove(str);
                    indices.add(word);
                    answer += word.length() + 1;
                    break;
                }
            }
            if(check == false) {
                indices.add(word);
                answer += word.length() + 1;
            }
        }
        return answer+1;
    }
}

> Result

 

> Recommend

import java.util.HashSet;

class Solution {
    public int minimumLengthEncoding(String[] words) {
        int sum = 0;
        HashSet<String> indices = new HashSet<>(Arrays.asList(words));
        for(String word : words){
            for(int idx = 1; idx < word.length(); idx++){
                indices.remove(word.substring(idx));
            }
        }
        for(String str : indices){
            sum += str.length() + 1;
        }
        return sum;
    }
}
728x90
반응형

+ Recent posts