判断通过操作能否让字符串相等 II
难度:
标签:
题目描述
You are given two strings s1
and s2
, both of length n
, consisting of lowercase English letters.
You can apply the following operation on any of the two strings any number of times:
- Choose any two indices
i
andj
such thati < j
and the differencej - i
is even, then swap the two characters at those indices in the string.
Return true
if you can make the strings s1
and s2
equal, and false
otherwise.
Example 1:
Input: s1 = "abcdba", s2 = "cabdab" Output: true Explanation: We can apply the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = "cbadba". - Choose the indices i = 2, j = 4. The resulting string is s1 = "cbbdaa". - Choose the indices i = 1, j = 5. The resulting string is s1 = "cabdab" = s2.
Example 2:
Input: s1 = "abe", s2 = "bea" Output: false Explanation: It is not possible to make the two strings equal.
Constraints:
n == s1.length == s2.length
1 <= n <= 105
s1
ands2
consist only of lowercase English letters.
代码结果
运行时间: 75 ms, 内存: 16.5 MB
/*
* 思路:
* 使用 Java Stream API 实现与上述相同的逻辑。
* 分别处理偶数下标和奇数下标的字符,并比较它们排序后的结果。
*/
import java.util.Arrays;
import java.util.stream.Collectors;
public class Solution {
public boolean canBeEqual(String s1, String s2) {
if (s1.length() != s2.length()) return false;
String s1Even = Arrays.stream(s1.split(""))
.filter((s, i) -> i % 2 == 0)
.sorted()
.collect(Collectors.joining());
String s1Odd = Arrays.stream(s1.split(""))
.filter((s, i) -> i % 2 != 0)
.sorted()
.collect(Collectors.joining());
String s2Even = Arrays.stream(s2.split(""))
.filter((s, i) -> i % 2 == 0)
.sorted()
.collect(Collectors.joining());
String s2Odd = Arrays.stream(s2.split(""))
.filter((s, i) -> i % 2 != 0)
.sorted()
.collect(Collectors.joining());
return s1Even.equals(s2Even) && s1Odd.equals(s2Odd);
}
}
解释
方法:
此题解采用的方法是通过计数比较。给定的操作允许我们交换字符串中索引i和j的字符,条件是j-i为偶数。这意味着可以在偶数索引位置自由交换字符,同样也可以在奇数索引位置自由交换。因此,只需要检查s1与s2在所有偶数位置的字符集合是否相同,以及所有奇数位置的字符集合是否相同。题解使用Counter类从collections模块来计数各个字符在偶数和奇数位置上的出现频次,只有当s1和s2在偶数位置和奇数位置的字符计数完全相同时,才能通过上述操作使s1变为s2。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在这个问题中,只考虑偶数索引和奇数索引的字符集合是否相同就足以判断两个字符串是否可以通过特定交换操作变得相同?
▷🦆
在使用Counter来比较两个字符串的字符频次时,是否考虑了字符的具体位置,还是仅仅比较了偶数和奇数位置上字符的总体频次?
▷🦆
假设输入的字符串中包含重复的字符,这种情况下Counter的比较是否仍然有效?
▷🦆
题解中是否考虑了如果字符串长度非常大时,对内存和性能的影响?
▷