The title
You are given a string word with subscripts starting at 0 and a character ch. Find the subscript I of the first occurrence of ch and invert the character in Word from subscript 0 to subscript I, including subscript I. If the character CH does not exist in Word, no operation is required.
For example, if word = “abcdefd” and ch = “d”, then you should reverse from subscript 0 to subscript 3 (including 3). The resulting string will be “dcbaefd”. Returns the result string.
Example 1: Input: word = "abcdefd", ch = "d" Output: "dcbaefd" Explanation: "d" first appears at subscript 3. Invert the character from subscript 0 to subscript 3 inclusive, resulting in the string "dcbaefd". Example 2: Input: word = "xyxzxe", ch = "z" Output: "zxyxxe" Explanation: The first and only occurrence of "z" is at subscript 3. Invert the character from subscript 0 to subscript 3, resulting in the string "zxyxxe". Example 3: Input: word = "abcd", ch = "z" Output: "abcd" Explanation: "z" does not exist in word. There is no need to reverse, and the resulting string is "abcd".Copy the code
Tip:
1 <= word. Length <= 250 Word consists of lowercase letters. Ch is a lowercase letter
Their thinking
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
try:
index = word.index(ch)
res = word[:index+1][::-1]
res += word[index+1:]
# print(res)
return res
except:
return word
if __name__ == '__main__':
# word = "abcdefd"
# ch = "d"
word = "abcd"
ch = "z"
result = Solution().reversePrefix(word,ch)
print(result)
Copy the code