蓝桥杯每日题目
1.(哈希表)
给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。
若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。
示例 1:
输入:words = ["w","wo","wor","worl", "world"]
输出:"world"
解释: 单词"world"可由"w", "wo", "wor", 和 "worl"逐步添加一个字母组成。
示例 2:
输入:words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出:"apple"
解释:"apply" 和 "apple" 都能由词典中的单词组成。但是 "apple" 的字典序小于 "apply"
import java.util.Arrays;import java.util.HashSet;import java.util.Set;class ggg { public String longestWord(String[] words) { Arrays.sort(words, (a, b) -> { if (a.length() != b.length()) { return a.length() - b.length(); } else { return b.compareTo(a); } }); String longest = ""; Set set = new HashSet(); set.add(""); int n = words.length; for (int i = 0; i < n; i++) { String word = words[i]; if (set.contains(word.substring(0, word.length() - 1))) { set.add(word); longest = word; } } return longest; }}
2.深度优先搜索
小朋友 A 在和 ta 的小伙伴们玩传信息游戏,游戏规则如下:
有 n 名玩家,所有玩家编号分别为 0 ~ n-1,其中小朋友 A 的编号为 0
每个玩家都有固定的若干个可传信息的其他玩家(也可能没有)。传信息的关系是单向的(比如 A 可以向 B 传信息,但 B 不能向 A 传信息)。
每轮信息必须需要传递给另一个人,且信息可重复经过同一个人
给定总玩家数 n,以及按 [玩家编号,对应可传递玩家编号] 关系组成的二维数组 relation。返回信息从小 A (编号 0 ) 经过 k 轮传递到编号为 n-1 的小伙伴处的方案数;若不能到达,返回 0。
示例 1:
输入:n = 5, relation = [[0,2],[2,1],[3,4],[2,3],[1,4],[2,0],[0,4]], k = 3
输出:3
解释:信息从小 A 编号 0 处开始,经 3 轮传递,到达编号 4。共有 3 种方案,分别是 0->2->0->4, 0->2->1->4, 0->2->3->4。
示例 2:
输入:n = 3, relation = [[0,2],[2,1]], k = 2
输出:0
解释:信息不能从小 A 处经过 2 轮传递到编号 2
import java.util.ArrayList;import java.util.List;class aa { int count,n,k; List<List> res; public int numWays(int n, int[][] relation, int k) { count = 0; this.k = k; this.n = n; res = new ArrayList<List>(); int len = relation.length; for(int i = 0;i < n;i++) { res.add(new ArrayList()); } for(int[] arr : relation) { int a = arr[0],b = arr[1]; res.get(a).add(b); } dfs(0,0); return count; } public void dfs(int index,int steps) { if(steps == k) { if(index == n - 1) count++; return; } List list = res.get(index); for(int next : list) { dfs(next,steps + 1); } }}