import java.util.LinkedList; import java.util.Scanner; import java.util.TreeSet; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); System.out.println(getResult(s)); } public static String getResult(String s) { StringBuilder sb = new StringBuilder(); LinkedList<TreeSet<Character>> eqs = new LinkedList<>(); boolean isOpen = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(') { isOpen = true; eqs.add(new TreeSet<>()); } else if (c == ')') { isOpen = false; if (eqs.getLast().size() == 0) eqs.removeLast(); } else { if (!isOpen) sb.append(c); else eqs.getLast().add(c); } } outer: while (true) { for (int i = 0; i < eqs.size(); i++) { for (int j = i + 1; j < eqs.size(); j++) { if (canCombine(eqs.get(i), eqs.get(j))) { eqs.get(i).addAll(eqs.get(j)); eqs.remove(j); continue outer; } } } break; } char[] cArr = sb.toString().toCharArray(); for (TreeSet<Character> eq : eqs) { Character t = eq.first(); for (int i = 0; i < cArr.length; i++) { if (eq.contains(cArr[i])) cArr[i] = t; } } String ans = new String(cArr); return ans.length() == 0 ? "0" : ans; } public static boolean canCombine(TreeSet<Character> set1, TreeSet<Character> set2) { for (char c = 'a'; c <= 'z'; c++) { char uc = (char) (c - 32); if ((set1.contains(c) || set1.contains(uc)) && (set2.contains(c) || set2.contains(uc))) { return true; } } return false; } }翻译成C++
时间: 2024-04-16 16:25:12 浏览: 121
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
string getResult(string s) {
string ans;
vector<set<char>> eqs;
bool isOpen = false;
for (int i = 0; i < s.length(); i++) {
char c = s[i];
if (c == '(') {
isOpen = true;
eqs.push_back(set<char>());
} else if (c == ')') {
isOpen = false;
if (eqs.back().empty()) eqs.pop_back();
} else {
if (!isOpen) ans += c;
else eqs.back().insert(c);
}
}
while (true) {
bool combined = false;
for (int i = 0; i < eqs.size(); i++) {
for (int j = i + 1; j < eqs.size(); j++) {
if (canCombine(eqs[i], eqs[j])) {
eqs[i].insert(eqs[j].begin(), eqs[j].end());
eqs.erase(eqs.begin() + j);
combined = true;
break;
}
}
if (combined) break;
}
if (!combined) break;
}
for (char& c : ans) {
for (const set<char>& eq : eqs) {
char t = *eq.begin();
if (eq.count(c)) c = t;
}
}
return ans.empty() ? "0" : ans;
}
bool canCombine(const set<char>& set1, const set<char>& set2) {
for (char c = 'a'; c <= 'z'; c++) {
char uc = toupper(c);
if ((set1.count(c) || set1.count(uc)) && (set2.count(c) || set2.count(uc))) {
return true;
}
}
return false;
}
int main() {
string s;
getline(cin, s);
cout << getResult(s) << endl;
return 0;
}
阅读全文