LeetCode 题解工作台

字符串及其反转中是否存在同一子字符串

给你一个字符串 s ,请你判断字符串 s 是否存在一个长度为 2 的子字符串,在 s 反转后的字符串中也出现。 如果存在这样的子字符串,返回 true ;如果不存在,返回 false 。 示例 1: 输入: s = "leetcode" 输出: true 解释: 子字符串 "ee" 的长度为 2 ,…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们可以用一个哈希表或者二维数组 来存储字符串 反转后的所有长度为 的子字符串。 然后我们遍历字符串 ,对于每一个长度为 的子字符串,我们判断它是否在 中出现过,是则返回 `true`。否则,遍历结束后返回 `false`。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s ,请你判断字符串 s 是否存在一个长度为 2 的子字符串,在 s 反转后的字符串中也出现。

如果存在这样的子字符串,返回 true;如果不存在,返回 false

 

示例 1:

输入:s = "leetcode"

输出:true

解释:子字符串 "ee" 的长度为 2,它也出现在 reverse(s) == "edocteel" 中。

示例 2:

输入:s = "abcba"

输出:true

解释:所有长度为 2 的子字符串 "ab""bc""cb""ba" 也都出现在 reverse(s) == "abcba" 中。

示例 3:

输入:s = "abcd"

输出:false

解释:字符串 s 中不存在满足「在其反转后的字符串中也出现」且长度为 2 的子字符串。

 

提示:

  • 1 <= s.length <= 100
  • 字符串 s 仅由小写英文字母组成。
lightbulb

解题思路

方法一:哈希表或数组

我们可以用一个哈希表或者二维数组 stst 来存储字符串 ss 反转后的所有长度为 22 的子字符串。

然后我们遍历字符串 ss,对于每一个长度为 22 的子字符串,我们判断它是否在 stst 中出现过,是则返回 true。否则,遍历结束后返回 false

时间复杂度 O(n)O(n),空间复杂度 O(Σ2)O(|\Sigma|^2)。其中 nn 为字符串 ss 的长度;而 Σ\Sigma 为字符串 ss 的字符集,本题中 Σ\Sigma 为小写英文字母,所以 Σ=26|\Sigma| = 26

1
2
3
4
5
class Solution:
    def isSubstringPresent(self, s: str) -> bool:
        st = {(a, b) for a, b in pairwise(s[::-1])}
        return any((a, b) in st for a, b in pairwise(s))
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Can the candidate efficiently implement a hash table-based solution?

  • question_mark

    Does the candidate show an understanding of string reversal and substring comparison?

  • question_mark

    Is the candidate able to optimize the solution with respect to time and space complexity?

warning

常见陷阱

外企场景
  • error

    Not reversing the string before comparison, which leads to incorrect results.

  • error

    Incorrectly checking substrings, leading to missing valid matches.

  • error

    Using inefficient data structures for substring lookup, causing slower solutions.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider substrings of length 3 instead of 2.

  • arrow_right_alt

    Check if there are any substrings of length 2 that are palindromes.

  • arrow_right_alt

    Optimize the solution by reducing the space complexity of the hash table.

help

常见问题

外企场景

字符串及其反转中是否存在同一子字符串题解:哈希·表·结合·string | LeetCode #3083 简单