소프트웨어에 대한 모든 것

LeetCode 풀기 - 1844. Replace All Digits with Characters 본문

알고리즘/LeetCode

LeetCode 풀기 - 1844. Replace All Digits with Characters

앤테바 2021. 11. 5. 20:44
반응형

1844. Replace All Digits with Characters

https://leetcode.com/problems/replace-all-digits-with-characters/

 

Replace All Digits with Characters - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1)

  • ord(), chr()에 대한 이해가 필요
    • ord() : character을 ascii value로 변환
    • chr() : integer를 charager로 변환
class Solution:
    def replaceDigits(self, s: str) -> str:
        ret = []
        for i, c in enumerate(s):
            if i % 2 == 0: 
                ret.append(c)
            else:
                ret.append(chr(ord(ret[-1]) + int(c)))
        return ''.join(ret)

솔루션2)

class Solution:
    def replaceDigits(self, s: str) -> str:
        arr = list(s)
        for i in range(1, len(arr), 2):
            arr[i] = chr(ord(arr[i - 1]) + int(arr[i]))
        return ''.join(arr)

 

반응형
Comments