
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace Question Symbols to Avoid Consecutive Repeating Characters in Python
Suppose we have a lowercase string s that contains only letters and '?' character, we have to convert all '?' characters into lower case letters such that the final string will not have any consecutive repeating characters. If there is more than one solution, return any of them.
So, if the input is like s = "hel??", then the output will be helab, se first question mark may be anything except 'l' and when first one is given, then second one can be anything except 'a'.
To solve this, we will follow these steps −
-
if size of s is same as 1, then
-
if s is same as "?", then
return "a"
return s
-
s := list of characters present in s
-
for i in range 0 to size of s - 1, do
-
if s[i] is same as "?", then
-
if i is same as 0 and s[i+1] is same as "?", then
s[i] := "a"
-
otherwise when i is same as 0 and s[i+1] is same as "a", then
s[i] := "b"
-
otherwise when i is same as 0, then
s[i] := "a"
-
otherwise when i is same as (size of s)-1 and s[i-1] is same as "a", then
s[i] := "b"
-
otherwise when i is same as (size of s)-1, then
s[i] := "a"
-
otherwise when s[i-1] is same as "a" and s[i+1] is same as "?", then
s[i] := "b"
-
otherwise when s[i+1] is same as "?", then
s[i] := "a"
-
otherwise when (s[i-1] is same as "a" and s[i+1] is same as "b") or (s[i-1] is same as "b" and s[i+1] is same as "a"), then
s[i] := "c"
-
otherwise when s[i-1] or s[i+1] is "a", then
s[i] := "b"
-
otherwise,
s[i] := "a"
-
-
return s after joining characters into string
Example (Python)
Let us see the following implementation to get better understanding −
def solve(s): if len(s) == 1 : if s == "?": return "a" return s s = list(s) for i in range(len(s)): if s[i] == "?": if i == 0 and s[i+1] == "?": s[i] = "a" elif i == 0 and s[i+1] == "a": s[i] = "b" elif i == 0: s[i] = "a" elif i == len(s)-1 and s[i-1] == "a": s[i] = "b" elif i == len(s)-1: s[i] = "a" elif s[i-1] == "a" and s[i+1] == "?": s[i] = "b" elif s[i+1] == "?": s[i] = "a" elif (s[i-1] == "a" and s[i+1] == "b") or (s[i-1] == "b" and s[i+1] == "a"): s[i] = "c" elif "a" in (s[i-1],s[i+1]): s[i] = "b" else: s[i] = "a" return "".join(s) s = "hel??" print(solve(s))
Input
"hel??"
Output
helab