Given an array
You may return the answer in any order.
A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.You may return the answer in any order.
Example 1:
Input: s={"bella","label","roller"} Output: common={"e","l","l"}
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class FindCommonChar {public static void main(String[] args) {String s[] = { "bella", "label", "roller" };List<String> common = commonChars(s);System.out.println(Arrays.asList(common));}static List<String> commonChars(String[] s) {int n = s.length;int f[][] = new int[n][26];for (int i = 0; i < n; i++)for (int j = 0; j < 26; j++)f[i][j] = 0;for (int i = 0; i < n; i++) {String x = s[i];for (int j = 0; j < x.length(); j++)f[i][x.charAt(j) - 'a']++;}List<String> res = new ArrayList<String>();for (int j = 0; j < 26; j++) {char c = '\0';int min1 = Integer.MAX_VALUE;for (int i = 0; i < n; i++) {if (f[i][j] < min1) {min1 = f[i][j];c = (char) ('a' + j);}}if (min1 != 0) {String s1 = String.valueOf(c);while (min1 > 0) {min1--;res.add(s1);}}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<string> commonChars(vector<string>& s){int n=s.size();int f[n][26];for(int i=0;i<n;i++)for(int j=0;j<26;j++)f[i][j]=0;for(int i= 0;i<n;i++){string x=s[i];for(int j=0;j<x.size();j++)f[i][x[j]-'a']++;}vector<string> res;for(int j=0;j<26;j++){char c;int min1=INT_MAX;for(int i=0;i<n;i++){if(f[i][j]<min1){min1=f[i][j];c='a'+j;}}if(min1!=0){string s1(1, c);while(min1--){res.push_back(s1);}}}return res;}int main(){vector<string> s={"bella","label","roller"};vector<string> common=commonChars(s);for(int i=0;i<common.size();i++)cout<<common[i]<<" ";return 0;}
No comments:
Post a Comment