Stay button 1160-- spell words

Give you a "Glossary" (array of strings) words and an "alphabet" (string) chars, if you can spell with the chars in the "letter" (character) in the words of a "word" (string), 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.

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.
Input: words = [ "hello", "world", "leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
may form a string "hello" and "world", so the answer is 5 + 5 = 10.

Problem-solving ideas:
apply for an equal length and the alphabet mark arrays, each letter in turn and comparing each with the alphabet of each word, and if they match, it will mark set with an array of 1 means that the position compare the letters of a word in the position of not compare. In this way until the end of
the implementation code:

int countCharacters(char ** words, int wordsSize, char * chars){
 int collen = 0;
 int len = strlen(chars) + 1;
 char* colsize;
 int* flag = (int*)malloc(len * 4);
 int k;
 int count = 0;
 int flag1 = 0;
 for (int i = 0; i<wordsSize; i++) {
  colsize = words[i];
  for (int z = 0; z<len; z++) {
   flag[z] = 0;
  }
  flag1 = 0;
  for (collen = 0; colsize[collen]; collen++);
  //每个单词的元素提出来比较
  for (int j = 0; j<collen; j++) {
   for (k = 0; k<len; k++) {
    if (words[i][j] == chars[k] && flag[k] == 0) {
     flag[k] = 1;
     break;
    }
    else {
     continue;
    }
   }
   if (k == len) {
    flag1 = 1;
    break;
   }
  }
  if (flag1 != 1) {
   count += collen;
  }
 }
 free(flag);
 return count;
}

Test results:
Here Insert Picture Description

Published 22 original articles · won praise 1 · views 255

Guess you like

Origin blog.csdn.net/scacacac/article/details/104925977