LeetCode 题解工作台

两个字符串的排列差

给你两个字符串 s 和 t ,每个字符串中的字符都不重复,且 t 是 s 的一个排列。 排列差 定义为 s 和 t 中每个字符在两个字符串中位置的绝对差值之和。 返回 s 和 t 之间的 排列差 。 示例 1: 输入: s = "abc", t = "bac" 输出: 2 解释: 对于 s = "a…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们可以使用哈希表或者一个长度为 的数组 来存储字符串 中每个字符的位置。 然后遍历字符串 ,计算每个字符在字符串 中的位置与在字符串 中的位置之差的绝对值之和即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个字符串 st,每个字符串中的字符都不重复,且 ts 的一个排列。

排列差 定义为 st 中每个字符在两个字符串中位置的绝对差值之和。

返回 st 之间的 排列差

 

示例 1:

输入:s = "abc", t = "bac"

输出:2

解释:

对于 s = "abc"t = "bac",排列差是:

  • "a"s 中的位置与在 t 中的位置之差的绝对值。
  • "b"s 中的位置与在 t 中的位置之差的绝对值。
  • "c"s 中的位置与在 t 中的位置之差的绝对值。

即,st 的排列差等于 |0 - 1| + |1 - 0| + |2 - 2| = 2

示例 2:

输入:s = "abcde", t = "edbac"

输出:12

解释: st 的排列差等于 |0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12

 

提示:

  • 1 <= s.length <= 26
  • 每个字符在 s 中最多出现一次。
  • ts 的一个排列。
  • s 仅由小写英文字母组成。
lightbulb

解题思路

方法一:哈希表或数组

我们可以使用哈希表或者一个长度为 2626 的数组 d\textit{d} 来存储字符串 s\textit{s} 中每个字符的位置。

然后遍历字符串 t\textit{t},计算每个字符在字符串 t\textit{t} 中的位置与在字符串 s\textit{s} 中的位置之差的绝对值之和即可。

时间复杂度 O(n)O(n),其中 nn 为字符串 s\textit{s} 的长度。空间复杂度 O(Σ)O(|\Sigma|),其中 Σ\Sigma 为字符集,这里是小写英文字母,所以 Σ26|\Sigma| \leq 26

1
2
3
4
5
class Solution:
    def findPermutationDifference(self, s: str, t: str) -> int:
        d = {c: i for i, c in enumerate(s)}
        return sum(abs(d[c] - i) for i, c in enumerate(t))
speed

复杂度分析

指标
时间complexity is O(n) for building the hash table and iterating through t, where n is the length of the strings. Space complexity is O(n) to store character-to-index mappings.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if candidates immediately use a mapping to avoid nested loops.

  • question_mark

    Listen for mentions of absolute differences and character positions.

  • question_mark

    Observe whether they consider constraints like single occurrence of characters.

warning

常见陷阱

外企场景
  • error

    Using nested loops to search indices instead of a hash table, causing O(n^2) time.

  • error

    Forgetting that t is always a permutation of s, leading to unnecessary checks.

  • error

    Incorrectly summing differences without taking absolute values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow characters to repeat and calculate permutation difference accordingly.

  • arrow_right_alt

    Return an array of individual differences for each character instead of the sum.

  • arrow_right_alt

    Compute permutation difference for multiple pairs of strings in batch efficiently.

help

常见问题

外企场景

两个字符串的排列差题解:哈希·表·结合·string | LeetCode #3146 简单