判断通过操作能否让字符串相等 I
难度:
标签:
题目描述
You are given two strings s1
and s2
, both of length 4
, 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 thatj - i = 2
, 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 = "abcd", s2 = "cdab" Output: true Explanation: We can do the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = "cbad". - Choose the indices i = 1, j = 3. The resulting string is s1 = "cdab" = s2.
Example 2:
Input: s1 = "abcd", s2 = "dacb" Output: false Explanation: It is not possible to make the two strings equal.
Constraints:
s1.length == s2.length == 4
s1
ands2
consist only of lowercase English letters.
代码结果
运行时间: 28 ms, 内存: 0.0 MB
/*
* 思路:
* 利用Java Stream API,我们可以通过将字符串转换为字符流并检查相应的条件来实现相同的逻辑。
* 通过对字符流进行过滤和匹配,可以验证是否存在符合交换条件的字符对。
*/
import java.util.stream.IntStream;
public class Solution {
public boolean canTransform(String s1, String s2) {
if (s1.equals(s2)) {
return true;
}
return IntStream.range(0, 4)
.filter(i -> i % 2 == 0)
.allMatch(i -> s1.charAt(i) == s2.charAt(i + 2) && s1.charAt(i + 2) == s2.charAt(i)) &&
IntStream.range(1, 4)
.filter(i -> i % 2 != 0)
.allMatch(i -> s1.charAt(i) == s2.charAt(i + 2) && s1.charAt(i + 2) == s2.charAt(i));
}
}
解释
方法:
这个题解的核心思路是分别比较字符串s1和s2中对应的可以通过特定操作(相隔两个位置的字符交换)交换的字符组。具体来说,s1和s2中的第一个字符与第三个字符可以互换,第二个字符与第四个字符可以互换。因此,题解检查了s1中的第一个字符和第三个字符是否能和s2中的第一个和第三个字符匹配(无论是原始顺序还是交换顺序),并且同样的检查对第二个和第四个字符进行了。只有两组字符都能匹配,函数才会返回true。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在字符串长度为4的限制下,只考虑交换具有特定间隔(j - i = 2)的字符就足够了,而不考虑其他位置的字符?
▷🦆
在解法中,你是如何确定只需要检查第一与第三个字符,以及第二与第四个字符之间的交换,就可以覆盖所有可能的情况?
▷🦆
这种解法是否具有普适性,即如果字符串长度变化或者交换规则改变(比如允许任意距离的交换),解法还会有效吗?
▷🦆
如果两个字符串有相同的字符但顺序不同,该算法是否还能正确判断?例如,s1为'aabb',s2为'bbaa',这种情况下该方法是否仍然适用?
▷