[Offer] wins the spelling of a word (one question per day)

Topic links: spell the word


Meaning of the questions: give you a "Glossary" (array of strings) words and an "alphabet" (string) chars.

If you can spell out words in a "word" (string) with the chars in the "letter" (character), then we think you've mastered the word.

Note: Each time the spelling, chars each letter can only be used once.

Return vocabulary words in all the words you have mastered the sum of the lengths.

 

Solution: violence. Similar hash? The number of chars with an array of statistics, and then copy this array, each time to traverse words in the word, does not appear on the same mark. You can successfully traverse on the record about the length of this word.

 


Code:

 1 class Solution {
 2 public:
 3     int mp[26] = {0};   
 4 
 5     int countCharacters(vector<string>& words, string chars) {
 6         int len = chars.size();
 7         for(int i = 0; i < len; i++){
 8             mp[chars[i] - 'a']++;
 9         }   //统计
10 
11         int ans = 0;
12         int res[26];    //复制表
13         for(int i = 0; i < words.size(); i++){
14             string word = words[i];
15             memcpy(res,mp,sizeof(mp));
16             int flag = 1;
17             for(int j = 0 ; j < word.size(); j++){
18                 if(res[word[j] - 'a'] == 0){    // If there is no letter 
. 19                      In Flag = 0 ;
 20 is                      BREAK ;
 21 is                  }
 22 is                  the else     RES [Word [J] - ' A ' ] - ;
 23 is              }
 24              IF (In Flag) + ANS = word.size ();
 25          }
 26 is  
27          return ANS;
 28      }
 29 };

 

Guess you like

Origin www.cnblogs.com/Asumi/p/12513682.html