Leetcode 2937. Make Three Strings Equal
You are given three binary strings s1, s2, and target, of the same length. The goal is to make the strings s1 and s2 equal to the target string by performing the following operation any number of times (possibly zero times):
s1 or s2 and replace it with its complement (‘0’ becomes ‘1’ and ‘1’ becomes ‘0’).Return true if you can make both s1 and s2 equal to target, and false otherwise.
s1, s2, and target?
s1 or s2.To solve this problem, follow these steps:
Position Analysis:
Compare each character position i of s1, s2, and target.
s1[i] and s2[i] equal to target[i]:
target[i] == '0', then both s1[i] and s2[i] should be convertible to ‘0’. This means s1[i] and s2[i] can be either ‘0’ or ‘1’, but not both being ‘1’ at the same time (because flipping one will make it zero).target[i] == '1', then at least one of s1[i] or s2[i] should be ‘1’.false.s1 = “1100”, s2 = “1010”, target = “1010”
target is ‘1’ and one of s1 or s2 has ‘1’, which is valid.target is ‘0’ and both s1 and s2 have ‘0’ or one can be made ‘0’; valid.target is ‘1’ and one of s1 or s2 has ‘1’; valid.target is ‘0’ and both s1 and s2 have ‘0’ or one can be made ‘0’; valid.#include <iostream>
#include <string>
bool makeStringsEqual(std::string s1, std::string s2, std::string target) {
int n = s1.size();
for (int i = 0; i < n; ++i) {
char t = target[i];
if (t == '0') {
if (s1[i] == '1' && s2[i] == '1') {
return false;
}
} else if (t == '1') {
if (s1[i] == '0' && s2[i] == '0') {
return false;
}
}
}
return true;
}
int main() {
std::string s1 = "1100", s2 = "1010", target = "1010";
std::cout << std::boolalpha << makeStringsEqual(s1, s2, target) << std::endl; // Output: true
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?