题目描述:
给你一个字符串数组
words
,请你找出所有在words
的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。示例 1:
输入:words = ["bella","label","roller"] 输出:["e","l","l"]示例 2:
输入:words = ["cool","lock","cook"] 输出:["c","o"]提示:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
由小写英文字母组成
Java 题解 及思路:
package com.java.leetcode.hash;
import java.util.ArrayList;
import java.util.List;
/**
* 题目描述
* 给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
*
*
* 示例 1:
*
* 输入:words = ["bella","label","roller"]
* 输出:["e","l","l"]
* 示例 2:
*
* 输入:words = ["cool","lock","cook"]
* 输出:["c","o"]给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
*
*
* 示例 1:
*
* 输入:words = ["bella","label","roller"]
* 输出:["e","l","l"]
* 示例 2:
*
* 输入:words = ["cool","lock","cook"]
* 输出:["c","o"]
*/
public class commonChars1002 {
/**
* 思路: 是列表字符串中 所有字符串中都有的字符串字段
* 1、 hash 表 存储 所有字符和存在的次数 ,其中所有字段取对应min的值(决定单个字符出现频次)
*
* @param A
* @return
*/
public List<String> commonChars(String[] A){
int[]hash=new int[26];
List<String> result = new ArrayList<>();
// 第一个字符串进行填充
for(int i=0;i<A[0].length();i++){
hash[A[0].charAt(i)-'a']++;
}
// 获取对比 hash shuzu
for(int i=1;i<A.length;i++){
int[] otherHash=new int[26];
for(int j=0;j<A[i].length();j++){
otherHash[A[i].charAt(j)-'a']++;
}
//获取每个位置最小值
for(int k=0;k<26;k++){
hash[k]=Math.min(hash[k],otherHash[k]);
}
}
// 遍历hash 节点 数据填入数组即可
for(int l=0;l<26;l++){
while(hash[l]!=0){
char c=(char)(l+'a');
result.add(String.valueOf(c));
hash[l]--;
}
}
return result;
}
}