[LeetCode] 2000. 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” 。
返回 结果字符串 。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-prefix-of-word
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
题意不难理解,反转 input 字符串的某一个前缀,返回反转之后的结果。需要考虑的 corner case 是如果字符串中不存在目标字母,则返回原字符串。一般的 case 是如果找到了目标字母第一次出现的位置 i,则对这个前缀 (0, i) 进行反转,与字符串剩余的部分拼接好之后返回即可。
复杂度
时间O(n)
空间O(n) - StringBuilder
代码
Java实现
1 |
|
再提供一个第一次写的像X一样的代码
Java实现
1 |
|