Post

leetcode(리트코드)-1576 Replace All'?s to Avoid Consecutive Repeating Characters(PYTHON)

leetcode 1576 - Replace All’?s to Avoid Consecutive Repeating Characters 문제입니다.

1. 문제

https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/


2. Input , Output


3. 분류 및 난이도

Eazy 난이도 문제입니다.


4. 문제 해석

  • 문자열에 대해 “?”에 임의의 문자를 넣습니다.
  • 단 왼쪽 문자와 오른쪽 문자와 같으면은 안됩니다.

5. code

코드설명

  • 랜덤함수 사용.

python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import random
class Solution:
    def modifyString(self, s: str) -> str:
        res = ""
        left = 0 
        right = 0
        for i in range(len(s)):
            if s[i] == "?" : 
                if i!= 0 : 
                    left = ord(res[i-1])
                if i!= len(s)-1 :
                    right = ord(s[i+1])
                rand = random.randrange(97,122)
                while rand == left or rand == right :
                    rand = random.randrange(97,122)
                res += chr(rand)
            else : res += s[i]
        return res
                
                    

6. 결과 및 후기, 개선점

필요시 c++로 짜드립니다.

설명이 필요하다면 댓글을 달아주세요.

This post is licensed under CC BY 4.0 by the author.