Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-05-01 10:03:52
https://leetcode.com/problems/reverse-prefix-of-word
2000. Reverse Prefix of Word
给定一string与一character 找到该character 假定该character的index为i
翻转word[0]到[i]并回传 假设无该character 回传原word
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.
思路:
遍历字串寻找字母 开个list记录找过的字母
找到目标字母就翻转list然后加上没找过的部分并回传
没找到回传原字串
Python Code:
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
result = []
for i in range(len(word)):
if word[i] == ch:
result.append(word[i])
return "".join(reversed(result))+word[i+1:]
result.append(word[i])
return word
作者: SecondRun (雨夜琴声)   2024-05-01 10:09:00
大师 放假还刷
楼主: sustainer123 (caster)   2024-05-01 10:14:00
快变无业游民了 姆咪
作者: JIWP (JIWP)   2024-05-01 10:19:00
大师,你今年毕业?
楼主: sustainer123 (caster)   2024-05-01 10:29:00
对 今年
作者: digua (地瓜)   2024-05-01 10:45:00
这上礼拜期中有考欸我不会写

Links booklink

Contact Us: admin [ a t ] ucptt.com