Hash Table: Spell the word (3.17 leetcode daily punch)

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.
 
Example 1:
Input: words = [ "cat", "bt", "hat", "tree"], chars = "atach"
Output: 6
Explanation:
may form a string "cat" and "hat", so the answer is 3 + 3 = 6.

Example 2:
Input: words = [ "hello", "world", "leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
may form a string "hello" and "world", so the answer is 5 + 5 = 10.

 
prompt:

 . 1 <= words.length <= 1000
 . 1 <= words [I] .length, chars.length <= 100
 all strings are only lowercase letters
 
Ideas: just know today is applying a hash table is to create a table, direct access to the data elements based on key values ​​(eg ASCLL code), and then achieve rapid look-up table. Thinking this question is first recorded alphanumeric alphabet, and compare each word root, cp letter appears once in the array minus one number on the corresponding letter, if there is a value less than 0 then out of the loop, At this time, the re-determined words [i] [j] whether \ 0, it means no not traversed to the end, it is not a complete word, the cycle continues, otherwise the string length plus.
. 1  int countCharacters ( char ** words, int wordsSize, char * chars)
 2  {
 . 3      int charsElemNum [ 26 is ] = { 0 };
 . 4      int length = 0 ;
 . 5      int I, J;
 . 6  
. 7      for (J = 0 ; chars [J]; J ++) // for alphabet letters counted 
. 8      {
 . 9          charsElemNum [chars [J] - 97 ] ++ ;
 10      }
 . 11      int CP [26 is ];
 12 is  
13 is      for (I = 0 ; I <wordsSize; I ++ )
 14      {
 15          for (J = 0 ; J < 26 is ; J ++ )
 16          {
 . 17              CP [J] = charsElemNum [J];   // copy alphabet the element 
18 is          }
 . 19          
20 is          for (J = 0 ; words [I] [J]; J ++ )
 21 is          {
 22 is              CP [words [I] [J] - 97 ] - ;
 23 is              IF (CP [words [I] [J] - 97] < 0)
24             break;
25         }
26 
27         if (words[i][j] != '\0')
28             continue;
29         else
30             length += j;
31     }
32 
33     return length;
34 }

 

 

 

Guess you like

Origin www.cnblogs.com/ZhengLijie/p/12508751.html