LeetCode 题解工作台

反转单词前缀

给你一个下标从 0 开始的字符串 word 和一个字符 ch 。找出 ch 第一次出现的下标 i , 反转 word 中从下标 0 开始、直到下标 i 结束(含下标 i )的那段字符。如果 word 中不存在字符 ch ,则无需进行任何操作。 例如,如果 word = "abcdefd" 且 ch …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们先找到字符 第一次出现的下标 ,然后反转从下标 开始、直到下标 结束(含下标 )的那段字符,最后将反转后的字符串与下标 $i + 1$ 开始的字符串拼接即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串 word 和一个字符 ch 。找出 ch 第一次出现的下标 i反转 word 中从下标 0 开始、直到下标 i 结束(含下标 i )的那段字符。如果 word 中不存在字符 ch ,则无需进行任何操作。

  • 例如,如果 word = "abcdefd"ch = 'd' ,那么你应该 反转 从下标 0 开始、直到下标 3 结束(含下标 3 )。结果字符串将会是 "dcbaefd"

返回 结果字符串

 

示例 1:

输入:word = "abcdefd", ch = 'd'
输出:"dcbaefd"
解释:"d" 第一次出现在下标 3 。 
反转从下标 0 到下标 3(含下标 3)的这段字符,结果字符串是 "dcbaefd" 。

示例 2:

输入:word = "xyxzxe", ch = 'z'
输出:"zxyxxe"
解释:"z" 第一次也是唯一一次出现是在下标 3 。
反转从下标 0 到下标 3(含下标 3)的这段字符,结果字符串是 "zxyxxe" 。

示例 3:

输入:word = "abcd", ch = 'z'
输出:"abcd"
解释:"z" 不存在于 word 中。
无需执行反转操作,结果字符串是 "abcd" 。

 

提示:

  • 1 <= word.length <= 250
  • word 由小写英文字母组成
  • ch 是一个小写英文字母
lightbulb

解题思路

方法一:模拟

我们先找到字符 chch 第一次出现的下标 ii,然后反转从下标 00 开始、直到下标 ii 结束(含下标 ii)的那段字符,最后将反转后的字符串与下标 i+1i + 1 开始的字符串拼接即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 wordword 的长度。

1
2
3
4
5
class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        i = word.find(ch)
        return word if i == -1 else word[i::-1] + word[i + 1 :]
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate can quickly identify the problem's two-pointer scanning approach.

  • question_mark

    Candidate efficiently handles cases where the target character does not exist in the string.

  • question_mark

    Candidate implements the in-place reversal technique without using unnecessary extra space.

warning

常见陷阱

外企场景
  • error

    Failing to handle the case where the target character does not exist in the string.

  • error

    Not reversing the string in place, leading to extra space usage.

  • error

    Overcomplicating the solution by using additional data structures instead of two-pointer scanning.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider handling multiple occurrences of the target character and reversing up to the last occurrence.

  • arrow_right_alt

    Extend the problem by allowing the user to reverse the segment up to a specified index instead of just the first occurrence.

  • arrow_right_alt

    Consider reversing substrings from any starting index to a given character index.

help

常见问题

外企场景

反转单词前缀题解:双·指针·invariant | LeetCode #2000 简单