这是我参与更文挑战的第2天,活动详情查看: 更文挑战
描述
Given a string s containing only lower case English letters and the '?' character, convert all the '?' characters into lower case letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.
It is guaranteed that there are no consecutive repeating characters in the given string except for '?'.
Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.
Example 1:
Input: s = "?zs"
Output: "azs"
Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".
Example 2:
Input: s = "ubv?w"
Output: "ubvaw"
Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".
Example 3:
Input: s = "j?qg??b"
Output: "jaqgacb"
Example 4:
Input: s = "??yw?ipkj?"
Output: "acywaipkja"
Note:
1 <= s.length <= 100
s contains only lower case English letters and '?'.
解析
根据题意,就是将 ? 替换成其他字母,保证其和前后的字母都不相同即可满足题意。思路比较简单,要特别注意边界条件的设置,如问号在开头或者结尾的地方,或者在字符串中一连好几个问号等等。先将 26 个所有的小写英文字母都罗列在 chars 中,然后遍历字符串 s ,如果字符不是问号就继续进行,如果是问号就在 chars 中随机抽一个和前后都不相同的字符替换掉问号,遍历结束得到的就是答案。
解答
class Solution(object):
def modifyString(self, s):
"""
:type s: str
:rtype: str
"""
if s == '?':
return 'a'
if s.count('?') == 0:
return s
s = list(s)
chars = 'abcdefghijklmnopqrstuvwxyz'
for i,c in enumerate(s):
if c!="?":
continue
else:
r = random.choice(chars)
while r == s[i-1] or r == s[(i+1)%len(s)]:
r = random.choice(chars)
s[i] = r
return "".join(s)
运行结果
Runtime: 16 ms, faster than 88.81% of Python online submissions for Replace All ?'s to Avoid Consecutive Repeating Characters.
Memory Usage: 13.3 MB, less than 88.09% of Python online submissions for Replace All ?'s to Avoid Consecutive Repeating Characters.
原题链接:leetcode.com/problems/re…
您的支持是我最大的动力