LeetCode 2896: Apply Operations to Make Two Strings Equal
Problem Description
Explanation:
To solve this problem, we need to find the minimum cost needed to make two binary strings s1
and s2
equal by applying specific operations. We can achieve this by iterating over both strings and comparing character by character. We consider two scenarios for each mismatch:
-
If
s1[i]
is different froms2[i]
:- If we can flip adjacent characters in
s1
, we choose the operation with the minimum cost. - If we can flip characters at arbitrary indices in
s1
, we choose the operation with the minimum cost. - If neither operation is possible, we return -1.
- If we can flip adjacent characters in
-
If
s1[i]
is the same ass2[i]
, we move to the next character.
Finally, we return the total cost required to make the strings equal or -1 if it is impossible.
Time Complexity: O(n) where n is the length of the strings s1
and s2
.
Space Complexity: O(1)
:
Solutions
class Solution {
public int getMinCost(String s1, String s2, int x) {
int cost = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
if (i + 1 < s1.length() && s1.charAt(i + 1) == s2.charAt(i + 1)) {
cost += Math.min(x, 2);
i++;
} else if (x < 2) {
cost += x;
} else {
return -1;
}
}
}
return cost;
}
}
Loading editor...