日期:2014-05-20 浏览次数:20746 次
public class A { public String[] getSameAppearWord(String[] strs) { List<String> list = new ArrayList<String>(); if(strs.length>0) { Set<String> haveWord = this.getHaveWord(strs[0]); for(String word : haveWord) { boolean allHave = true; for(String oneStr : strs) { if(oneStr.indexOf(word) == -1) { allHave = false; break; } } if(allHave) list.add(word); } } return list.toArray(new String[]{}); } //看第一个字符串中不重复的字符有哪些 private Set<String> getHaveWord(String word) { Set<String> set = new HashSet<String>(); if(word.length()>0) { for(int i=0;i<word.length()-1;i++) { set.add(word.substring(i,i+1)); } } return set; } public static void main(String[] args) { String a = "aaabbcc"; String b = "addffc" ; String c = "eeffac" ; String[] strs = {a,b,c}; A test = new A(); String[] sameAppearWord = test.getSameAppearWord(strs); for(String str : sameAppearWord) System.out.println(str); } }
------解决方案--------------------
public class TestSameChar { /** * 判断多个字符串中重复的字符,并打印输出 * @param args */ public static void main(String[] args) { String a = "aaabbccfe"; String b = "addffe"; String c = "eeffa"; String totalString[] = {a, b, c}; //先将多个字符串归并到一个字符串数组中,方便取用 //字符串数组用来判断下一个取的字符是否已经在数组中存在,如果是则代表取的是重复的字符,直接跳过 char[] arr = new char[a.length()]; System.out.println("重复的字符为:"); for(int i=0; i<a.length(); i++) { boolean f = true; //f代表是否找到重复的字符 char ch = a.charAt(i); if(!isContains(arr, ch)) { //判断是否取到了重复的字符 arr[i] = ch; //如果没有,则先将其存储到字符数组中 for(int j=1; j<totalString.length; j++) { //循环遍历每一个字符串数组 if(totalString[j].indexOf(ch) == -1) { f = false; break; } } if(f) System.out.print(ch + " "); } } } private static boolean isContains(char[] arr, char c) { for(int i=0; i<arr.length; i++) { if(arr[i] == c) return true; } return false; } }
------解决方案--------------------