[알고리즘] LeetCode - Longest String Chain

Jerry·2021년 9월 10일
0

LeetCode

목록 보기
73/73
post-thumbnail

LeetCode - Longest String Chain

문제 설명

You are given an array of words where each word consists of lowercase English letters.

wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.

For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.

Return the length of the longest possible word chain with words chosen from the given list of words.

입출력 예시

Example 1:

Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: One of the longest word chains is ["a","ba","bda","bdca"].

Example 2:

Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].

제약사항

1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i] only consists of lowercase English letters.

Solution

[전략]
1. 문자열의 길이가 짧은 순으로 정렬
2. 각 문자열을 순회하며
3. 해당 문자열에서 문자를 하나씩 삭제한 문자열이 문자열 리스트에 있는지 확인(HashMap 사용)
4. 문자열을 순회하며 HashMap에 넣을때 연속적인 최대 체인 길이를 value로 넣음

import java.util.*;

class Solution {
    public int longestStrChain(String[] words) {

        HashMap<String, Integer> promiseStrs = new HashMap<>();

        Arrays.sort(words, (a, b) -> a.length() - b.length());

        int maxLen = 1;
        for (String word : words) {
            int subMaxLen = 1;
            for (int i = 0; i < word.length(); i++) {
                StringBuilder sb = new StringBuilder(word);
                sb.deleteCharAt(i);
                String extractedStr = sb.toString();
                if (promiseStrs.containsKey(extractedStr)) {
                    subMaxLen = Math.max(subMaxLen, promiseStrs.get(extractedStr) + 1);
                    maxLen = Math.max(maxLen, subMaxLen);
                }
            }
            promiseStrs.put(word, subMaxLen);
        }

        return maxLen;
    }
}
profile
제리하이웨이

0개의 댓글