1 题目
LeetCode
给定一个字符串数组,找出其中全部字符串都有出现的字符,如果全部字符串同时包含多个也要输出重复的。
2 解
2.1 HashMap
用HashMap数组为每一行保存一个HashMap<Character,Integer>,出现新字符就保存,已有字符就将整型加一,然后遍历第一个字符串中的字符,以该字符为准,先初始化count为0,遍历HashMap数组中对应行的map,找到了先判断是否为0,判断为0可以正确地统计重复的字符,非0说明该字符串还有未统计过的目标字符,则count++并将map中对应的值减一,如果没找到可以直接break跳出,跳出后判断 count 和 A[0].length 是否相等,相等说明该字符在全部字符串都有出现,加入到List中,第一个字符串遍历结束以后就结束了。返回List。
public List<String> commonChars(String[] A) {
if(A.length==0 || A[0].length()==0)
return null;
List<String> list=new ArrayList<>();
if(A.length==1){
//字符串数组仅有一个字符串,所有该字符串的字符都符合条件
for(int i=0;i<A[0].length();i++){
list.add(String.valueOf(A[0].charAt(i)));
}
return list;
}
//字符串数组有多个字符串,因为要找到每个字符串中都有的字符,所以以第一个字符串中的字符为准即可
//创建HashMap数组,为每一个字符串创建一个map,便于查询和修改
HashMap[] maps=new HashMap[A.length];
for(int i=0;i<A.length;i++){
maps[i]=new HashMap<Character,Integer>();
for(int j=0;j<A[i].length();j++){
//已包含则加一
if(maps[i].containsKey(A[i].charAt(j))){
int temp=(int)maps[i].get(A[i].charAt(j))+1;
maps[i].put(A[i].charAt(j),temp);
}else
maps[i].put(A[i].charAt(j),1);
}
}
//遍历一次第一个字符串
for(int i=0;i<A[0].length();i++){
int count=1;
for(int j=1;j<A.length;j++){
//当前字符串包含目标字符
if(maps[j].containsKey(A[0].charAt(i)) && (int)maps[j].get(A[0].charAt(i))!=0 ){
count++;
int temp=(int)maps[j].get(A[0].charAt(i))-1;
maps[j].put(A[0].charAt(i),temp);
}else
//不包含,直接跳出
break;
}
if(count==A.length)
list.add(String.valueOf(A[0].charAt(i)));
}
return list;
}
2.2 官解
官解使用了一个 minfreq[]数组保存每个字符出现的最小次数,用 fre[]数组 暂存每个字符串的次数,遍历字符串后将minfreq[]更新为两个数组中较小的一个,最后将 minfreq[]中非零项加入list中,有多少就加入多少个。
public List<String> commonChars(String[] A) {
int[] minfreq = new int[26];
Arrays.fill(minfreq, Integer.MAX_VALUE);
for (String word: A) {
int[] freq = new int[26];
int length = word.length();
for (int i = 0; i < length; ++i) {
char ch = word.charAt(i);
++freq[ch - 'a'];
}
for (int i = 0; i < 26; ++i) {
minfreq[i] = Math.min(minfreq[i], freq[i]);
}
}
List<String> ans = new ArrayList<String>();
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < minfreq[i]; ++j) {
ans.add(String.valueOf((char) (i + 'a')));
}
}
return ans;
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/find-common-characters/solution/cha-zhao-chang-yong-zi-fu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3 收获
3.1 HashMap数组
HashMap[] arr=new HashMap[11];
arr[0]=new HashMap< K , V >();
3.2 String与char
char的包装类为 Character。
String中取出char用 charAt() 方法,参数是该char的下标。
char转成String用 String.valueOf()方法,参数是该char。
String中的内容不可改变。