LeetCode 题解工作台

判断通过操作能否让字符串相等 I

给你两个字符串 s1 和 s2 ,两个字符串的长度都为 4 ,且只包含 小写 英文字母。 你可以对两个字符串中的 任意一个 执行以下操作 任意 次: 选择两个下标 i 和 j 且满足 j - i = 2 ,然后 交换 这个字符串中两个下标对应的字符。 如果你可以让字符串 s1 和 s2 相等,那么返…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们观察题目中的操作,可以发现,如果字符串的两个下标 和 的奇偶性相同,那么它们可以通过交换改变顺序。 因此,我们可以统计两个字符串中奇数下标的字符的出现次数,以及偶数下标的字符的出现次数,如果两个字符串的统计结果相同,那么我们就可以通过操作使得两个字符串相等。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个字符串 s1 和 s2 ,两个字符串的长度都为 4 ,且只包含 小写 英文字母。

你可以对两个字符串中的 任意一个 执行以下操作 任意 次:

  • 选择两个下标 i 和 j 且满足 j - i = 2 ,然后 交换 这个字符串中两个下标对应的字符。

如果你可以让字符串 s1  s2 相等,那么返回 true ,否则返回 false 。

 

示例 1:

输入:s1 = "abcd", s2 = "cdab"
输出:true
解释: 我们可以对 s1 执行以下操作:
- 选择下标 i = 0 ,j = 2 ,得到字符串 s1 = "cbad" 。
- 选择下标 i = 1 ,j = 3 ,得到字符串 s1 = "cdab" = s2 。

示例 2:

输入:s1 = "abcd", s2 = "dacb"
输出:false
解释:无法让两个字符串相等。

 

提示:

  • s1.length == s2.length == 4
  • s1 和 s2 只包含小写英文字母。
lightbulb

解题思路

方法一:计数

我们观察题目中的操作,可以发现,如果字符串的两个下标 iijj 的奇偶性相同,那么它们可以通过交换改变顺序。

因此,我们可以统计两个字符串中奇数下标的字符的出现次数,以及偶数下标的字符的出现次数,如果两个字符串的统计结果相同,那么我们就可以通过操作使得两个字符串相等。

时间复杂度 O(n+Σ)O(n + |\Sigma|),空间复杂度 O(Σ)O(|\Sigma|)。其中 nn 是字符串的长度,而 Σ\Sigma 是字符集。

相似题目:

1
2
3
4
5
6
class Solution:
    def canBeEqual(self, s1: str, s2: str) -> bool:
        return Counter(s1[::2]) == Counter(s2[::2]) and Counter(s1[1::2]) == Counter(
            s2[1::2]
        )
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate understands the string-driven solution approach.

  • question_mark

    Candidate suggests efficient ways to handle small input sizes.

  • question_mark

    Candidate proposes checking string rotations or character set equivalence as a strategy.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the problem by using unnecessary algorithms or data structures.

  • error

    Failing to consider small input sizes which allow for brute-force solutions.

  • error

    Not checking for rotations or permutations of strings which could offer a simpler solution.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    If strings are of larger length, brute force would not be feasible, and more efficient algorithms are required.

  • arrow_right_alt

    A variant might include using recursion to repeatedly swap characters until a solution is found.

  • arrow_right_alt

    Testing performance with larger strings as input can provide insight into optimal solution techniques.

help

常见问题

外企场景

判断通过操作能否让字符串相等 I题解:String-driven solution … | LeetCode #2839 简单