StringBuilder VI
Another problem that leads to TLE if using standard string (remember that string concatenation is very costly since there are multiple objects being created), but if you switch to StringBuilder, which allows you to make changes to its elements (it isn't immutable), you can achieve a very quick result. Using it and at the very end convert it to regular String. Code is down below, cheers, ACC.
Maximum Bitwise XOR After Rearrangement - LeetCode
You are given two binary strings s and t, each of length n.
You may rearrange the characters of t in any order, but s must remain unchanged.
Return a binary string of length n representing the maximum integer value obtainable by taking the bitwise XOR of s and rearranged t.
Example 1:
Input: s = "101", t = "011"
Output: "110"
Explanation:
- One optimal rearrangement of
tis"011". - The bitwise XOR of
sand rearrangedtis"101" XOR "011" = "110", which is the maximum possible.
Example 2:
Input: s = "0110", t = "1110"
Output: "1101"
Explanation:
- One optimal rearrangement of
tis"1011". - The bitwise XOR of
sand rearrangedtis"0110" XOR "1011" = "1101", which is the maximum possible.
Example 3:
Input: s = "0101", t = "1001"
Output: "1111"
Explanation:
- One optimal rearrangement of
tis"1010". - The bitwise XOR of
sand rearrangedtis"0101" XOR "1010" = "1111", which is the maximum possible.
Constraints:
1 <= n == s.length == t.length <= 2 * 105s[i]andt[i]are either'0'or'1'.
public class Solution {
public string MaximumXor(string s, string t)
{
int countOnes = t.Where(c => c == '1').Count();
int countZeroes = t.Where(c => c == '0').Count();
StringBuilder retVal = new StringBuilder(s);
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '0')
{
if (countOnes > 0)
{
retVal[i] = '1';
countOnes--;
}
else
{
retVal[i] = '0';
countZeroes--;
}
}
else
{
if (countZeroes > 0)
{
retVal[i] = '1';
countZeroes--;
}
else
{
retVal[i] = '0';
countOnes--;
}
}
}
return retVal.ToString();
}
}

Comments
Post a Comment