Java|Java 第 24 课 888. 公平的糖果棒交换 720. 词典中最长的单词


第 24 课

  • [888. 公平的糖果棒交换](https://leetcode-cn.com/problems/fair-candy-swap/)
  • [720. 词典中最长的单词](https://leetcode-cn.com/problems/longest-word-in-dictionary/)
【Java|Java 第 24 课 888. 公平的糖果棒交换 720. 词典中最长的单词】
888. 公平的糖果棒交换
class Solution: def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]: a, b = sum(aliceSizes), sum(bobSizes) c, d = aliceSizes, set(bobSizes) for i in c: j = (b - a)//2 + i if j in d: return [i, j]

class Solution { public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { int a = 0, b = 0; for (int x : aliceSizes) a += x; Set d = new HashSet(); for (int x : bobSizes){ b += x; d.add(x); } int delta = (b - a) / 2; for (int i : aliceSizes){ int j = delta + i; if (d.contains(j)) return new int[]{i, j}; } return new int[2]; } }

720. 词典中最长的单词
class Solution(object): def longestWord(self, words): wordset = set(words) words.sort(key = lambda c: (-len(c), c)) for word in words: if all(word[:k] in wordset for k in range(1, len(word))): return wordreturn ""

class Solution { public String longestWord(String[] words) { Set set = new HashSet<>(); for (String w : words) set.add(w); Arrays.sort(words); // 先按字母升序排序再按长度降序排列 Arrays.sort(words, (a, b) -> b.length() - a.length()); sign: for (String word : words){ for (int i = 1; i < word.length(); i++){ if (!set.contains(word.substring(0, i))) continue sign; } return word; } return ""; } }class Solution { public String longestWord(String[] words) { Arrays.sort(words, (a, b) -> { // 升序 if (a.length() != b.length()) return a.length() - b.length(); return b.compareTo(a); // 相同长度下把字典序较大的排在前面 }); String ans = ""; Set set = new HashSet<>(); set.add(""); for (String word : words) { if (set.contains(word.substring(0, word.length() - 1))) { ans = word; set.add(word); // 注意是逐步多一,所以,这个添加要放在 if 里面 } } return ans; } }

    推荐阅读