Count the Number of Consistent Strings

You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed

Find the number of consistent strings in the array words

Example 1:

Input: allowed="ab",words[]={"ad","bd","aaab","baa","badab"}
Output: 3
Explanation: "aaab" , "baa" these are contains all characters same as allowed string

Approach:

Java

public class CountConsistentStrings {
    public static void main(String[] args) {
        String allowed = "ab";
        String words[] = { "ad""bd""aaab"
            "baa""badab" };
        System.out.println(countConsistentStrings(allowed,
             words));
    }

    public static int countConsistentStrings(String allowed
                String[] words) {
        int count = 0;
        for (int i = 0; i < words.length; i++) {
            int nc = 0;
            String str = words[i];
            for (int j = 0; j < str.length(); j++) {
                if (!allowed.contains(String.valueOf(
                        str.charAt(j))))
                    nc++;
            }
            if (nc == 0)
                count++;
        }

        return count;
    }
}

C++

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

//function to count the consistent strings

int countConsistentStrings(string allowed
        vector<string>& words
{
        int cnt=0;
        set<charst;
        for(int i=0;i<allowed.size();i++)
               st.insert(allowed[i]);
        for(int i=0;i<words.size();i++)
        {
            int flag=0;
            for(int j=0;j<words[i].size();j++)
            {
                if(st.find(words[i][j])==st.end())
                {
                    flag=1;
                    break;
                }
            }
            if(flag==0)
                  cnt++;
        }
        return cnt;
    }
int main()
{
   string allowed="ab";
   vector<stringwords={"ad","bd","aaab","baa","badab"};
   int  count=countConsistentStrings(allowed,words);
   cout<<count<<"\n";
   return 0;
}





No comments:

Post a Comment