4.找字符串数组中所有字符串中都出现相同次数的字符

题目: 

public class FindCommonStrings {

	 public static List<String> commonChars(String[] A) {
		 	if(A.length<0||A.length>100){
		 		return null;
		 	}
		 	if(A[0].equals(""))
		 		return null;
		 	//暂存第一个字符串
		   	char[] s = A[0].toCharArray();
	        int j=1;
	        //保存结果
	        ArrayList<String> list = new ArrayList<String>();
	    
	        for(int i=0;i<s.length;i++){
	            //对第一个字符串的每个字符,找其他字符串里是否有出现过
	            for(j=1;j<A.length;j++){
	            	int index = A[j].indexOf(s[i]);
	            	//一旦没有出现过,就跳出循环,看下一个字符
	                if(index==-1){
	                    break;
	                }else{
	                	/*出现了s[i],把A[j]的当前的s[i]替换为空格
	                	因为有的字符可能在所有字符串里出现相同的次数,有的出现次数不一样,
	                	只有在所有字符串里出现相同次数的才是目标字符
	                	*/
	                	A[j]=A[j].replaceFirst(""+s[i], " ");
	                }
	            }
	            //有字符在所有字符串里均出现了
	            if(j==A.length){
	                list.add(s[i]+"");
	            }
	            
	        }
	        return list;
	  }
	 
	 public static void main(String[] args) {
		System.out.println(commonChars(new String[]{"cool","lock","cook"}).toString());
		System.out.println(commonChars(new String[]{"bella","label","roller"}).toString());
		
	}
}

猜你喜欢

转载自blog.csdn.net/cl723401/article/details/88104316
今日推荐