LeetCode1178. Word puzzle

Foreign friends have designed an English version of a word guessing game based on Chinese word puzzles. Please come and guess.

The puzzle of an anagram is given in the form of a string. If a word meets the following two conditions, then it can be counted as the answer:

The word word contains the first letter of the puzzle.
Every letter in the word word can be found in the puzzle.
For example, if the face of an anagram is "abcdefg", then the words that can be used as the answer are "faced", "cabbage", and "baggage"; while "beefed" (without the letter "a") and "based" "S" does not appear in the mystery) can not be used as the answer to the mystery.
Return an answer array answer, each element in the array answer[i] is the number of words corresponding to puzzles[i] in the given word list words.

Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle
Input:
words = ["aaaa","asas","able" ,"Ability","actt","actor","access"],
puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
Output: [1, 1,3,2,4,0]
Explanation:

1 个单词可以作为 "aboveyz" 的谜底 : "aaaa" 
1 个单词可以作为 "abrodyz" 的谜底 : "aaaa"
3 个单词可以作为 "abslute" 的谜底 : "aaaa", "asas", "able"
2 个单词可以作为 "absoryz" 的谜底 : "aaaa", "asas"
4 个单词可以作为 "actresz" 的谜底 : "aaaa", "asas", "actt", "access"
没有单词可以作为 "gaswxyz" 的谜底,因为列表中的单词都不含字母 'g'
class Solution {
    
    
public:
    vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) {
    
    
	vector<int> cnt;
	int len_w = words.size();
	int len_p = puzzles.size();
	map<int,int>mp;
	map<int,int>::iterator it;
	//排序后去除重复字符串
	for(int j=0; j<len_w; j++) {
    
    
		sort(words[j].begin(), words[j].end());  //先对字符串排序;
		string::iterator itend = unique(words[j].begin(),words[j].end());
		//返回出现重复元素的首地址;
		words[j].erase(itend, words[j].end());//删除重复元素;
		if(words[j].size()<=7) {
    
    
			int data=0;
			for(int k=0; k<words[j].size(); k++) {
    
    
				data+=pow(2,words[j][k]-'a');
			}
			mp[data]++;
		}
	}
	for(int j=0; j<len_p; j++) {
    
    
		int data=0;
		int count=0;
		int first_char = puzzles[j][0]-'a';
		for(int k=0; k<puzzles[j].size(); k++) {
    
    
			data+=pow(2,puzzles[j][k]-'a');
		}
		data-=pow(2,first_char);
		int substr=data;
		while(data>0) {
    
    
			int x=data+pow(2,first_char);
			if(mp[x]>0) {
    
    
				count+=mp[x];
			}
			data=(data-1) & substr;
			if(data == 0){
    
    
				x=data+pow(2,first_char);
				if(mp[x]>0) {
    
    
					count+=mp[x];
				}
			}
		}
		cnt.push_back(count);
	}
	return cnt;
    }
};

Guess you like

Origin blog.csdn.net/chaokudeztt/article/details/114176757