LeetCode1002(竞赛题):查找常用字符(给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。)

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。
 例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。你可以按任意顺序返回答案。

示例 1:
输入:["bella","label","roller"]
输出:["e","l","l"]

示例 2:
输入:["cool","lock","cook"]
输出:["c","o"]

总体思路:就是用字符串数组中的第一个字符串去和剩余的字符串比较,找出共有的字符,并计算出最小重复数量,再传到集合中去。

import java.util.*;

public class lianxi{
	public static void main(String[] args){
		Solution S = new Solution();
		String[] A = {"bella","label","roller"};
		List<String> list = S.commonChars(A);
		System.out.println(list);

	}
}

class Solution {
    public List<String> commonChars(String[] A) {
         List<String> list = new ArrayList<>();
        for(int j = 0; j < A[0].length(); j++){
        	//遍历第一个字符串中的字符
            int count = 0;//相同的字符最少重复几次
            char c = 'a';
            for(int i = 0; i < A.length-1; i++){
            	//遍历所有字符串
                int a = rechecking(A[0].charAt(j),A[i]);
                int b = rechecking(A[0].charAt(j),A[i+1]);
                c = A[0].charAt(j);
                if(a==0||b==0){
                	//只要a和b等于一次0  直接跳出   将count置零
                   count =0;
                   break;
                }
                if(count == 0){
                	//找出a和b最小的
                    if(a >= b){
                        count = b;
                    }
                    else{
                        count = a;
                    }
                }
                else{
                	//count不等于0  那么就是 a,b,count 三个做比较,找出最小的
                    if(a >= b){
                        if(count > b){
                        count = b;
                        }
                    }
                    else{
                        if(count > a ){
                        count = a;
                        }
                    }
                }
                
            }
            if(list.contains(String.valueOf(c)) == false && count > 0 ){
            	//判断字符是否已存在
                    while(count > 0){
                         list.add(String.valueOf(c));
                         count--;
                    }  
            }
        }
        return list;
    }
    public int rechecking(char chars, String s){
    	//用来比较每个字符串中有几个相同的字符
        int count = 0;
        for(int i = 0; i < s.length(); i++){
            if(chars == s.charAt(i)){
                count++;
            }
                
        }
        return count;
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值