思路导图 先用几个二维数组保存 abcd 用ASCII码保存在二维数组中
class Solution {
public List<String> commonChars(String[] A)
{
List<String> list = new ArrayList<String>();
int[][] arr = new int[A.length][26];
boolean bol = true ;
//将所有数据用二维数组保存
for (int x = 0; x < A.length ; x++)
{
for (int i = 0; i < A[x].length(); i++)
{
// System.out.println((A[x].charAt(i) - 'a')+" <-" + A[x].charAt(i));
arr[x][A[x].charAt(i) - 'a']++;
}
}
//开始逐个元素进行查看
for (int x = 0; x < 26; x++)
{
int count = arr[A.length - 1][x];
if (arr[A.length - 1][x] != 0)
{
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i][x] == 0) //如果有一个字符串某元素个数为0 不满足不成立
{
bol = false;
break;
}
count = Math.min(arr[i][x],count);//统计每个字符在每个字符串中出现次数
}
}
if(bol )
{
for (int temp = 0; temp < count; temp++)
{
// System.out.print((char)(x + 97));
list.add(""+(char)(x + 97));
}
}
count=0;
bol = true;
}
System.out.println();
for(int i = 0;i<arr.length;i++) {
for(int x = 0;x<26;x++) {
//System.out.print((char)(x+97)+"->"+arr[i][x]+" ");
}
//System.out.println();
}
return list;
}
}
HashMap 一开始写不出来 卡了很久
class Solution {
public List<String> commonChars(String[] A) {
List<String> result = new ArrayList();
List<HashMap<Character, Integer>> list = new ArrayList();
for (String word: A) {
HashMap<Character, Integer> table = new HashMap();//以字符串的形式保存到HashMap中
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) + 1);//新的getOrDefault()方法提供一个快捷的方式获取Map中的值
}
list.add(table);
}
HashMap<Character, Integer> map = list.get(0);
for (Character ch: map.keySet()) {
boolean flag = true;
int min = map.get(ch);
for (int i = 1; i < list.size(); i++) {
HashMap<Character, Integer> charCnt = list.get(i);
if (!charCnt.containsKey(ch)) {
flag = false;
break;
}
if (charCnt.get(ch) < min) {
min = charCnt.get(ch);
}
}
if (flag) {
for (int j = 0; j < min; j++) {
result.add("" + ch);
}
}
}
return result;
}
}