Find Words That Can Be Formed by Characters

You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Find the sum of lengths of all good strings in words.

Example 1:

Input: words = {"cat","bt","hat","tree"}, chars = "atach"
Output: 6

Approach

Java


public class FindWordsFormedbyChar {
    public static void main(String[] args) {
        String words[] = { "cat""bt""hat""tree" };
        String chars = "atach";
        System.out.println(countCharacters(words, chars));
    }

    static int countCharacters(String[] wordsString chars) {
        int n = words.length;
        int m = chars.length();
        int f[] = new int[26];
        int f1[] = new int[26];
        for (int i = 0; i < m; i++)
            f[chars.charAt(i) - 'a']++;
        for (int i = 0; i < 26; i++)
            f1[i] = f[i];
        int res = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 26; j++)
                f[j] = f1[j];
            int j = 0;
            String str = words[i];
            for (j = 0; j < str.length(); j++) {
                if (f[str.charAt(j) - 'a']>0)
                    f[str.charAt(j) - 'a']--;
                else
                    break;
                if (j == str.length() - 1)
                    res += str.length();
            }

        }
        return res;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int countCharacters(vector<string>& wordsstring chars
{
     int n=words.size();
     int m=chars.size();
     int f[26]={0},f1[26]={0};
     for(int i=0;i<m;i++)
           f[chars[i]-'a']++;
     for(int i=0;i<26;i++)
           f1[i]=f[i];
    int res=0;
     for(int i=0;i<n;i++)
     {
         for(int i=0;i<26;i++)
               f[i]=f1[i];
         int j=0;
         string str=words[i];
         for(j=0;j<str.size();j++)
         {
             if(f[str[j]-'a'])
                   f[str[j]-'a']--;
             else
                 break;
              if(j==str.size()-1)
                 res+=str.size();
         }
     
     }
        return res;
}
int main()
{
    vector<stringwords ={"cat","bt","hat","tree"};
    string chars = "atach";
    cout<<countCharacters(words,chars);
    return 0;
}


No comments:

Post a Comment