LeetCode 题解工作台
执行逐位运算使字符串相等
给你两个下标从 0 开始的 二元 字符串 s 和 target ,两个字符串的长度均为 n 。你可以对 s 执行下述操作 任意 次: 选择两个 不同 的下标 i 和 j ,其中 0 。 同时,将 s[i] 替换为 ( s[i] OR s[j] ) , s[j] 替换为 ( s[i] XOR s[j]…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · string·结合·位运算·操作
答案摘要
我们注意到 其实是数字转换的“工具”,因此只要两个字符串中都有 或者都没有 ,那么就可以通过操作使得两个字符串相等。 时间复杂度 ,其中 为字符串的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·位运算·操作 题型思路
题目描述
给你两个下标从 0 开始的 二元 字符串 s 和 target ,两个字符串的长度均为 n 。你可以对 s 执行下述操作 任意 次:
- 选择两个 不同 的下标
i和j,其中0 <= i, j < n。 - 同时,将
s[i]替换为 (s[i]ORs[j]) ,s[j]替换为 (s[i]XORs[j]) 。
例如,如果 s = "0110" ,你可以选择 i = 0 和 j = 2,然后同时将 s[0] 替换为 (s[0] OR s[2] = 0 OR 1 = 1),并将 s[2] 替换为 (s[0] XOR s[2] = 0 XOR 1 = 1),最终得到 s = "1110" 。
如果可以使 s 等于 target ,返回 true ,否则,返回 false 。
示例 1:
输入:s = "1010", target = "0110" 输出:true 解释:可以执行下述操作: - 选择 i = 2 和 j = 0 ,得到 s = "0010". - 选择 i = 2 和 j = 1 ,得到 s = "0110". 可以使 s 等于 target ,返回 true 。
示例 2:
输入:s = "11", target = "00" 输出:false 解释:执行任意次操作都无法使 s 等于 target 。
提示:
n == s.length == target.length2 <= n <= 105s和target仅由数字0和1组成
解题思路
方法一:脑筋急转弯
我们注意到 其实是数字转换的“工具”,因此只要两个字符串中都有 或者都没有 ,那么就可以通过操作使得两个字符串相等。
时间复杂度 ,其中 为字符串的长度。空间复杂度 。
class Solution:
def makeStringsEqual(self, s: str, target: str) -> bool:
return ("1" in s) == ("1" in target)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since we only scan both strings once to check presence of ones and zeros. Space complexity is O(1) if we only track flags for ones in s and target, without extra structures. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate immediately checks for impossible conversion when s has no ones and target does.
- question_mark
Candidate recognizes OR/XOR operations allow setting zeros to ones but never removing ones without a zero present.
- question_mark
Candidate explains linear scan suffices, no full operation simulation is required.
常见陷阱
外企场景- error
Forgetting that a string of all zeros cannot produce any ones, leading to incorrect true return.
- error
Attempting full simulation of all operations, which is unnecessary and inefficient.
- error
Misaligning indices when checking feasibility for target ones and s ones.
进阶变体
外企场景- arrow_right_alt
Consider applying similar bitwise operations on integer arrays instead of strings.
- arrow_right_alt
Allow operations only on adjacent indices to see how feasibility rules change.
- arrow_right_alt
Compute the minimum number of operations required to transform s into target.