[Leet Code] Reverse Prefix of Word

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".
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".
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".
class Solution(object):
def reversePrefix(self, word, ch):
"""
:type word: str
:type ch: str
:rtype: str
"""
index_of_word = word.find(ch)

if index_of_word == -1:
return word
else:
word = list(word)
decrementer = index_of_word
for i in range((index_of_word//2)+1):
temp = word[i]
word[i] = word[decrementer]
word[decrementer] = temp
decrementer -= 1
return "".join(word)

--

--

--

Learning, and posting my findings!

Love podcasts or audiobooks? Learn on the go with our new app.

S03E11: I am not a clever man

Visualizing Uncertainty

Participating in Hacktoberfest 2020 with Firefox Daylight

Discover Tiime Engine, Ternoa’s Community Rewards Platform

Starting From Zero with Modular Synthesis and VCV Rack

Calculate Your $NEPT Airdrop Shares

GitHub Issue Triage and Transparency

Kubernetes on Devstack part 4: Using OpenStack Magnum to create a Kubernetes cluster

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matthew Boyd

Matthew Boyd

Learning, and posting my findings!

More from Medium

Advent Of Copilot

Copilot becoming my friend

Easily convert Recursive solutions to Non-Recursive alternatives

Introduction To Binary Trees In Java

All about algorithms and functions