LeetCode 2546: Apply Bitwise Operations to Make Strings Equal
Problem Description
Explanation
To solve this problem, we can observe that the operations provided allow us to change the bits at different indices in the string s
. We need to determine if after performing these operations, we can transform s
into target
. We can achieve this by comparing the parity of set bits at each index in both strings. If the parity of set bits at each index matches, then it is possible to transform s
into target
.
- Iterate through each index of the strings
s
andtarget
. - Count the number of set bits at each index in both strings.
- If the parity of set bits at each index does not match, return false.
- If the parity of set bits at each index matches for all indices, return true.
Time Complexity: O(n) where n is the length of the strings s
and target
.
Space Complexity: O(1)
Solutions
class Solution {
public boolean canBeEqual(String s, String target) {
int n = s.length();
for (int i = 0; i < n; i++) {
if (Integer.bitCount(s.charAt(i) - '0') % 2 != Integer.bitCount(target.charAt(i) - '0') % 2) {
return false;
}
}
return true;
}
}
Loading editor...