Професионална програма
MartinBG avatar MartinBG 2790 Точки
Best Answer

The problem is on line #55:

msg = msg.replace(toCut, "").concat(new StringBuilder(toCut).reverse().toString());

String#replace method "Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence." while the task is to "... replace only the first occurrence of the given substring if there are more than one such occurrences."


String#replaceFirst method should be used instead for this task:

msg = msg.replaceFirst(toCut, "").concat(new StringBuilder(toCut).reverse().toString());


The change above will take you to 100/100 in Judge, but it will throw exception for any special character (like '?' which is used in Zero test #2) in toCut string as it is used as regex.

The simplest solution to this new problem is to use Pattern.quote:

msg = msg.replaceFirst(Pattern.quote(toCut), "").concat(new StringBuilder(toCut).reverse().toString());


As a bonus, this is the program refactored to use StringBuilder and BufferedReader which results in about 3 times faster execution according to Judge tests.

02/07/2020 05:07:20
Yargi avatar Yargi 14 Точки

Thank you very much for this answer and all your Posts in the forum. You allways deep explaining the Problem and your additional code examples are very nice to gain more experience. yes