코딩테스트 풀이/JAVA
[LeetCode/Easy] 1576. Replace All ?'s to Avoid Consecutive Repeating Characters
무지맘
2023. 4. 13. 12:38
1. Input
1) String s
2. Output
1) 다음 조건을 만족하면서 s에 있는 ?를 다른 영어 소문자로 바꾼 결과를 반환
- ?은 인접한 문자와 같은 것으로 바꿀 수 없다.
- ? 이외의 문자는 바꿀 수 없다.
3. Constraint
1) 1 <= s.length <= 100
2) s는 영어 소문자와 ?으로만 이루어져 있다.
4. Example
Input: s = "?zs" -> Output: "azs"
설명: bzs, czs, ..., yzs 모두 가능하다.
5. Code
1) 첫 코드(2023/04/13)
if(s.equals("?"))
return "a";
char[] c = s.toCharArray();
for(int i=0 ; i<c.length ; i++){
if(c[i]=='?'){
if(0<i && i<c.length-1){
c[i] = 'a';
while(c[i]==c[i-1] || c[i]==c[i+1])
c[i] = (char)((int)(Math.random()*26)+'a');
} else if(i==0){
if(c[1]=='a') c[i] = 'b';
else c[i] = 'a';
} else{
if(c[i-1]=='a') c[i] = 'b';
else c[i] = 'a';
}
}
}
return new String(c);