要求:给定字符串数组,找出各个字符串中出现的公共字符。
例子:给定字符串数组中有三个字符串"1233333", “2543”, “765432”,
输出字符’2’, ‘3’,输出字符的顺序不做要求。
import java.util.*;
public class CommonDigitFinder {
public static void main(String[] args) {
String[] strings = new String[]{"1233333", "2543", "765432"};
List<String> list = commonChars(strings);
System.out.println(list);
}
public static List<String> commonChars(String[] A) {
List<String> list = new ArrayList<>();
int maxIndex = 0;
for (int i = 0; i < A.length; i++) {
if (A[i].length() > A[maxIndex].length()) {
maxIndex = i;
}
}
for (int i = 0; i < A[maxIndex].length(); i++) {
boolean allHave = true;
for (int j = 0; j < A.length; j++) {
if (j != maxIndex) {
StringBuilder sb = new StringBuilder(A[j]);
int k = 0;
for (k = 0; k < sb.length(); k++) {
if ((k == sb.length() - 1) && sb.charAt(k) != A[maxIndex].charAt(i)) {
allHave = false;
}
if (sb.charAt(k) == A[maxIndex].charAt(i)) {
sb.delete(k, k + 1);
A[j] = String.valueOf(sb);
break;
}
}
}
}
if (allHave) {
list.add(String.valueOf(A[maxIndex].charAt(i)));
}
}
return list;
}
}