2546.执行逐位运算使字符串相等
链接:2546.执行逐位运算使字符串相等
难度:Medium
标签:位运算、字符串
简介:如果可以使 s 等于 target ,返回 true ,否则,返回 false 。
题解 1 - cpp
- 编辑时间:2023-01-22
- 执行用时:24ms
- 内存消耗:12.8MB
- 编程语言:cpp
- 解法介绍:判断两个字符串中是否都存在1。
class Solution {
public:
bool makeStringsEqual(string s, string target) {
int n = s.size();
bool s1 = false, t1 = false;
for (int i = 0; i < n; i++) {
if (s[i] == '1') s1 = true;
if (target[i] == '1') t1 = true;
if (s1 && t1) return true;
}
return s == target;
}
};
题解 2 - rust
- 编辑时间:2023-01-22
- 执行用时:4ms
- 内存消耗:2.6MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
pub fn make_strings_equal(s: String, target: String) -> bool {
s.contains('1') && target.contains('1') || s == target
}
}
题解 3 - cpp
- 编辑时间:2023-01-22
- 执行用时:16ms
- 内存消耗:12.8MB
- 编程语言:cpp
- 解法介绍:判断是否存在11,10和01的情况。
class Solution {
public:
bool makeStringsEqual(string s, string target) {
if (s == target) return true;
int n = s.size();
int s_has1 = 0, t_has1 = 0, has11 = 0, has01 = 0, has10 = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '1' && target[i] == '1') return true;
if (s[i] == '0' && target[i] == '1') {
has01++;
if (has10) return true;
}
if (s[i] == '1' && target[i] == '0') {
has10++;
if (has01) return true;
}
}
return false;
}
};
题解 4 - python
- 编辑时间:2023-01-22
- 执行用时:36ms
- 内存消耗:15.7MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
def makeStringsEqual(self, s: str, target: str) -> bool:
return ('1' in s) and ('1' in target) or s == target