You are given three strings s1
, s2
, and s3
. You have to perform the following operation on these three strings as many times as you want.
In one operation you can choose one of these three strings such that its length is at least 2
and delete the rightmost character of it.
Return the minimum number of operations you need to perform to make the three strings equal if there is a way to make them equal, otherwise, return -1
.
LeetCode Problem - 2937
class Solution {
// This method calculates the minimum number of operations required to make three strings identical by removing characters.
public int findMinimumOperations(String s1, String s2, String s3) {
// Find the length of the shortest string among s1, s2, and s3
int min = Math.min(s1.length(), Math.min(s2.length(), s3.length()));
// Variable to store the length of the common prefix among the three strings
int commonPrefix = 0;
// Iterate through the characters of the shortest string
for (int i = 0; i < min; i++) {
// If the characters at the same position in all three strings are equal, increment commonPrefix
if (s1.charAt(i) == s2.charAt(i) && s2.charAt(i) == s3.charAt(i))
commonPrefix++;
else
break; // If characters are not equal, break the loop
}
// If there is no common prefix among the strings, return -1
if (commonPrefix == 0)
return -1;
else
// Otherwise, return the total length of all three strings minus three times the length of the common prefix
return ((s1.length() + s2.length() + s3.length()) - 3 * commonPrefix);
}
}