[LeetCode] 1576. Replace All ?'s to Avoid Consecutive Repeating Characters

Chobby·2025년 9월 23일
1

LeetCode

목록 보기
551/582

😎풀이

  1. s 순회
  2. 현재 문자가 ?인지 확인
    2-1. 이전 문자 검사
    2-2. 다음 문자 검사
    2-3. 현재 문자와 비교
    2-4. 없는 문자라면 현재 자리에 해당 문자 추가
  3. 변환된 문자배열 결합
  4. 결합된 문자열 반환
function modifyString(s: string): string {
    const splitted = [...s]
    for(let i = 0; i < s.length; i++) {
        if(s[i] !== '?') continue
        const prev = splitted[i - 1]
        const prevCode = prev ? prev.charCodeAt(0) : -1
        const next = splitted[i + 1]
        const nextCode = next ? next.charCodeAt(0) : -2
        for(let curCode = 97; curCode <= 122; curCode++) {
            if(curCode === prevCode) continue
            if(curCode === nextCode) continue
            splitted[i] = String.fromCharCode(curCode)
            break
        }
    }
    return splitted.join("")
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글