加载中...
2000-反转单词前缀(Reverse Prefix of Word)
发表于:2021-12-03 | 分类: 简单
字数统计: 722 | 阅读时长: 3分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/reverse-prefix-of-word

英文原文

Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.

  • For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".

Return the resulting string.

 

Example 1:

Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3. 
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".

Example 2:

Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".

Example 3:

Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".

 

Constraints:

  • 1 <= word.length <= 250
  • word consists of lowercase English letters.
  • ch is a lowercase English letter.

中文题目

给你一个下标从 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 是一个小写英文字母

通过代码

高赞题解

解题思路

此处撰写解题思路
有两种情况:
1、word里面包含ch:此时只需要将ch的第一个位置找到然后之前的反转,之后的不变就可以。
2、word里面包含ch:直接将word输出即可。参看具体代码

代码

class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        
        fan_ = False
        for ii in range(len(word)):
            if word[ii] == ch:
                fan_ = True
                break
        if fan_:
            word = word[:ii+1][::-1] + word[ii+1:]
        return word

统计信息

通过次数 提交次数 AC比率
7811 10146 77.0%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1997-访问完所有房间的第一天(First Day Where You Have Been in All the Rooms)
下一篇:
2001-可互换矩形的组数(Number of Pairs of Interchangeable Rectangles)
本文目录
本文目录