Это проблема интервью, на которую я застрял:
Для строки, состоящей из a, b и c, мы можем выполнить следующую операцию: Возьмите любые два смежных отдельных символа и замените их третьим символом. Например, если "a" и "c" смежны, их можно заменить на "b". Какая наименьшая строка может возникнуть при повторном применении этой операции?
Мое решение:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
public class Solution {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
System.out.println(solve(in.readLine()));
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static int solve(String testCase) {
LinkedList<String> temp = new LinkedList<String>(deconstruct(testCase));
for (int i = 0; i < (temp.size() - 1); i++) {
if (!temp.get(i).equals(temp.get(i + 1))) {
temp.add(i, getThirdChar(temp.remove(), temp.remove()));
i = -1;
}
}
return reconstruct(temp).length();
}
private static List<String> deconstruct(String testCase) {
List<String> temp = new LinkedList<String>();
for (int i = 0; i < testCase.length(); i++) {
temp.add(testCase.charAt(i) + "");
}
return temp;
}
private static String reconstruct(List<String> temp) {
String testCase = "";
for (int i = 0; i < temp.size(); i++) {
testCase += temp.get(i);
}
return testCase;
}
private static String getThirdChar(String firstChar, String secondChar) {
return "abc".replaceAll("[" + firstChar + secondChar + "]+", "");
}
}
Код, похоже, отлично работает на тестовых входах "cab" (печатает "2" ), "bcab" (печатает "1" ) и "ccccc" (печатает "5" ). Но мне все время говорят, что мой код ошибочен. Может ли кто-нибудь помочь мне выяснить, где ошибка?