1178. 猜字谜

题目描述

外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。

字谜的迷面 puzzle 按字符串形式给出,如果一个单词 word 符合下面两个条件,那么它就可以算作谜底:

单词 word 中包含谜面 puzzle 的第一个字母。
单词 word 中的每一个字母都可以在谜面 puzzle 中找到。
例如,如果字谜的谜面是 “abcdefg”,那么可以作为谜底的单词有 “faced”, “cabbage”, 和 “baggage”;而 “beefed”(不含字母 “a”)以及 “based”(其中的 “s” 没有出现在谜面中)。
返回一个答案数组 answer,数组中的每个元素 answer[i] 是在给出的单词列表 words 中可以作为字谜迷面 puzzles[i] 所对应的谜底的单词数目。

链接:https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle

样例

输入:
words = [“aaaa”,“asas”,“able”,“ability”,“actt”,“actor”,“access”],
puzzles = [“aboveyz”,“abrodyz”,“abslute”,“absoryz”,“actresz”,“gaswxyz”]
输出:[1,1,3,2,4,0]
解释:
1 个单词可以作为 “aboveyz” 的谜底 : “aaaa”
1 个单词可以作为 “abrodyz” 的谜底 : “aaaa”
3 个单词可以作为 “abslute” 的谜底 : “aaaa”, “asas”, “able”
2 个单词可以作为 “absoryz” 的谜底 : “aaaa”, “asas”
4 个单词可以作为 “actresz” 的谜底 : “aaaa”, “asas”, “actt”, “access”
没有单词可以作为 “gaswxyz” 的谜底,因为列表中的单词都不含字母 ‘g’。

其中:
1 <= words.length <= 10^5
4 <= words[i].length <= 50
1 <= puzzles.length <= 10^4
puzzles[i].length == 7
words[i][j], puzzles[i][j] 都是小写英文字母。
每个 puzzles[i] 所包含的字符都不重复。
链接:https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle

思路

困难等级题目,原思路超时,这里贴上官方题解。

https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle/solution/cai-zi-mi-by-leetcode-solution-345u/

代码

public List<Integer> findNumOfValidWords(String[] words, String[] puzzles) {
		//哈希表
		Map<Integer,Integer> fre = new HashMap<Integer,Integer>();
		
		//遍历每一个word
		for(String word : words) {
			int mask = 0;
			for(int i = 0;i < word.length();i++) {
				char ch = word.charAt(i);
				mask |= (1 << (ch - 'a'));
			}
			//记录到哈希表中
			if(Integer.bitCount(mask) <= 7) {
				fre.put(mask, fre.getOrDefault(mask, 0) + 1);
			}
		}
		//结果列表
		List<Integer> ans = new ArrayList<Integer>();
		//遍历每个谜面
		for(String puzzle : puzzles) {
			int total = 0;
			int mask = 0;
			//不包括首字母 首字母后面再加
			for(int i = 1;i < 7;i++) {
				char ch = puzzle.charAt(i);
				mask |= (1 << (ch - 'a'));
			}
			int subset = mask;
			do {
				//子集再加上首字母
				int s = subset |(1 << (puzzle.charAt(0) - 'a'));
				if(fre.containsKey(s)) {
					total += fre.get(s);
				}
				//减一看下一个子集
				subset = (subset - 1) & mask;
			}while(subset != mask);
			//存入结果
			ans.add(total);
		}
		return ans;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值