public class SimplifyString {
@Test
public void test(){
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(get(s));
}
private String get(String s) {
String reg = "\\([a-zA-Z]*\\)";
Pattern compile = Pattern.compile(reg);
Matcher matcher = compile.matcher(s);
LinkedList<TreeSet<String>> equals = new LinkedList<>();
while (matcher.find()){
String group = matcher.group();
if (group.length() > 2){
TreeSet<String> set = Arrays.stream(group.substring(1, group.length() - 1).split(""))
.collect(Collectors.toCollection(TreeSet::new));
equals.add(set);
}
}
o : while (true){
if (equals.size() <= 1) break;
for (int i = 0; i < equals.size() - 1; i++) {
TreeSet<String> set1 = equals.get(i);
ArrayList<String> list1 = set1.stream().map(String::toUpperCase)
.collect(Collectors.toCollection(ArrayList::new));
for (int j = i + 1; j < equals.size(); j++) {
TreeSet<String> set2 = equals.get(j);
ArrayList<String> list2 = set2.stream().map(String::toUpperCase)
.collect(Collectors.toCollection(ArrayList::new));
if (!Collections.disjoint(list1, list2)){
set1.addAll(set2);
equals.remove(j);
continue o;
}
}
}
break;
}
String[] str = s.replaceAll(reg, "").split("");
if (str.length == 1 && "".equals(str[0])) return "0";
return Arrays.stream(str).map(ss -> {
for (TreeSet<String> equal : equals) {
if (equal.contains(ss)) return equal.first();
}
return ss;
}).collect(Collectors.joining());
}
}
new01_SimplifyString
于 2023-05-20 22:27:57 首次发布