Skip to content

Latest commit

 

History

History
357 lines (309 loc) · 9.58 KB

File metadata and controls

357 lines (309 loc) · 9.58 KB

English Version

题目描述

给出一个单词数组 words ,其中每个单词都由小写英文字母组成。

如果我们可以 不改变其他字符的顺序 ,在 wordA 的任何地方添加 恰好一个 字母使其变成 wordB ,那么我们认为 wordA 是 wordB 的 前身

  • 例如,"abc" 是 "abac" 的 前身 ,而 "cba" 不是 "bcad" 的 前身

词链是单词 [word_1, word_2, ..., word_k] 组成的序列,k >= 1,其中 word1 是 word2 的前身,word2 是 word3 的前身,依此类推。一个单词通常是 k == 1单词链 。

从给定单词列表 words 中选择单词组成词链,返回 词链的 最长可能长度
 

示例 1:

输入:words = ["a","b","ba","bca","bda","bdca"]
输出:4
解释:最长单词链之一为 ["a","ba","bda","bdca"]

示例 2:

输入:words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
输出:5
解释:所有的单词都可以放入单词链 ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].

示例 3:

输入:words = ["abcd","dbqca"]
输出:1
解释:字链["abcd"]是最长的字链之一。
["abcd","dbqca"]不是一个有效的单词链,因为字母的顺序被改变了。

 

提示:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 16
  • words[i] 仅由小写英文字母组成。

解法

方法一:排序 + 哈希表

我们先将所有单词按照长度排序,然后从短到长遍历每个单词,对于每个单词,我们枚举它的每个前身,如果前身存在,那么我们就可以将当前单词添加到该前身的后面形成一个更长的单词链,我们将该单词链的长度加一并更新答案。

时间复杂度 $(n \times (\log n + m^2))$,空间复杂度 $O(n)$。其中 $n$$m$ 分别是单词数组 words 的长度和单词的最大长度。

Python3

class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        def check(s: str, t: str) -> bool:
            m, n = len(s), len(t)
            i = j = 0
            while i < m and j < n:
                if s[i] == t[j]:
                    i += 1
                j += 1
            return i == m

        words.sort(key=len)
        f = [1] * len(words)
        d = defaultdict(list)
        for i, w in enumerate(words):
            for j in d[len(w) - 1]:
                if check(words[j], w):
                    f[i] = max(f[i], f[j] + 1)
            d[len(w)].append(i)
        return max(f)
class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        words.sort(key=len)
        d = defaultdict(int)
        ans = 0
        for s in words:
            x = 1
            for i in range(len(s)):
                t = s[:i] + s[i + 1:]
                x = max(x, d[t] + 1)
            d[s] = x
            ans = max(ans, x)
        return ans

Java

class Solution {
    public int longestStrChain(String[] words) {
        Arrays.sort(words, Comparator.comparingInt(String::length));
        int n = words.length;
        int[] f = new int[n];
        Arrays.fill(f, 1);
        List<Integer>[] g = new List[17];
        Arrays.setAll(g, k -> new ArrayList<>());
        int ans = 1;
        for (int i = 0; i < n; ++i) {
            String w = words[i];
            for (int j : g[w.length() - 1]) {
                if (check(words[j], w)) {
                    f[i] = Math.max(f[i], f[j] + 1);
                    ans = Math.max(ans, f[i]);
                }
            }
            g[w.length()].add(i);
        }
        return ans;
    }

    private boolean check(String s, String t) {
        int m = s.length(), n = t.length();
        int i = 0, j = 0;
        while (i < m && j < n) {
            if (s.charAt(i) == t.charAt(j)) {
                ++i;
            }
            ++j;
        }
        return i == m;
    }
}
class Solution {
    public int longestStrChain(String[] words) {
        Arrays.sort(words, Comparator.comparingInt(String::length));
        Map<String, Integer> d = new HashMap<>();
        int ans = 0;
        for (String s : words) {
            int x = 0;
            for (int i = 0; i < s.length(); ++i) {
                String t = s.substring(0, i) + s.substring(i + 1);
                x = Math.max(x, d.getOrDefault(t, 0) + 1);
            }
            d.put(s, x);
            ans = Math.max(ans, x);
        }
        return ans;
    }
}

C++

class Solution {
public:
    int longestStrChain(vector<string>& words) {
        sort(words.begin(), words.end(), [](auto& a, auto& b) { return a.size() < b.size(); });
        int n = words.size();
        int f[n];
        vector<int> g[17];
        int ans = 1;
        auto check = [](string& s, string& t) -> bool {
            int m = s.size(), n = t.size();
            int i = 0, j = 0;
            while (i < m && j < n) {
                if (s[i] == t[j]) {
                    ++i;
                }
                ++j;
            }
            return i == m;
        };
        for (int i = 0; i < n; ++i) {
            f[i] = 1;
            auto w = words[i];
            for (int j : g[w.size() - 1]) {
                if (check(words[j], w)) {
                    f[i] = max(f[i], f[j] + 1);
                    ans = max(ans, f[i]);
                }
            }
            g[w.size()].push_back(i);
        }
        return ans;
    }
};
class Solution {
public:
    int longestStrChain(vector<string>& words) {
        sort(words.begin(), words.end(), [](auto& a, auto& b) { return a.size() < b.size(); });
        int ans = 0;
        unordered_map<string, int> d;
        for (auto& s : words) {
            int x = 1;
            for (int i = 0; i < s.size(); ++i) {
                string t = s.substr(0, i) + s.substr(i + 1);
                x = max(x, d[t] + 1);
            }
            d[s] = x;
            ans = max(ans, x);
        }
        return ans;
    }
};

Go

func longestStrChain(words []string) int {
	sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
	n := len(words)
	f := make([]int, n)
	g := [17][]int{}
	ans := 1
	check := func(s, t string) bool {
		m, n := len(s), len(t)
		i, j := 0, 0
		for i < m && j < n {
			if s[i] == t[j] {
				i++
			}
			j++
		}
		return i == m
	}
	for i, w := range words {
		f[i] = 1
		for _, j := range g[len(w)-1] {
			if check(words[j], w) {
				f[i] = max(f[i], f[j]+1)
				ans = max(ans, f[i])
			}
		}
		g[len(w)] = append(g[len(w)], i)
	}
	return ans
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func longestStrChain(words []string) (ans int) {
	sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
	d := map[string]int{}
	for _, s := range words {
		x := 1
		for i := 0; i < len(s); i++ {
			t := s[:i] + s[i+1:]
			x = max(x, d[t]+1)
		}
		d[s] = x
		ans = max(ans, x)
	}
	return
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

TypeScript

function longestStrChain(words: string[]): number {
    words.sort((a, b) => a.length - b.length);
    let ans = 1;
    const n = words.length;
    const f: number[] = new Array(n).fill(1);
    const g: number[][] = new Array(17).fill(0).map(() => []);
    const check = (s: string, t: string): boolean => {
        const m = s.length;
        const n = t.length;
        let i = 0;
        let j = 0;
        while (i < m && j < n) {
            if (s[i] === t[j]) {
                ++i;
            }
            ++j;
        }
        return i === m;
    };
    for (let i = 0; i < n; ++i) {
        const w = words[i];
        for (const j of g[w.length - 1]) {
            if (check(words[j], w)) {
                f[i] = Math.max(f[i], f[j] + 1);
                ans = Math.max(ans, f[i]);
            }
        }
        g[w.length].push(i);
    }
    return ans;
}
function longestStrChain(words: string[]): number {
    words.sort((a, b) => a.length - b.length);
    let ans = 0;
    const d: Map<string, number> = new Map();
    for (const s of words) {
        let x = 1;
        for (let i = 0; i < s.length; ++i) {
            const t = s.slice(0, i) + s.slice(i + 1);
            x = Math.max(x, (d.get(t) || 0) + 1);
        }
        d.set(s, x);
        ans = Math.max(ans, x);
    }
    return ans;
}

...