와드의 블로그

99클럽 코테 스터디 33일차 TIL 본문

TIL

99클럽 코테 스터디 33일차 TIL

Ward 2024. 11. 29. 14:33

미들러

문제

신규 아이디 추천

# 문자열

https://school.programmers.co.kr/learn/courses/30/lessons/72410

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

풀이

아이디를 입력했을데 아이디를 변환과정에 따라 변환하여 알맞은 아이디를 반환하는 문제이다.

자바의 문자열 메서드들을 이용하여 문자열을 변환한다.

문자열의 삽입과 삭제가 빈번하게 발생하므로 StringBuilder를 사용한다.

코드

import java.util.*;

class Solution {
    public String solution(String new_id) {
        StringBuilder sb = new StringBuilder(new_id.toLowerCase());
        
        int i = 0;
        while (i < sb.length()) {
            char c = sb.charAt(i);
            if (!(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.')) {
                sb.deleteCharAt(i);
                continue;
            }
            i++;
        }
        
        i = 0;
        while (i < sb.length() - 1) {
            if (sb.charAt(i) == '.' && sb.charAt(i) == sb.charAt(i + 1)) {
                sb.deleteCharAt(i);
                continue;
            }
            i++;
        }
        

        if (sb.length() > 0 && sb.charAt(0) == '.')
            sb.deleteCharAt(0);
        if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '.')
            sb.deleteCharAt(sb.length() - 1);
        if (sb.length() == 0)
            sb.append("a");
        if (sb.length() >= 16) {
            sb.setLength(15);
            if (sb.charAt(14) == '.')
                sb.deleteCharAt(14);
        }
     
        while (sb.length() < 3)
            sb.append(sb.charAt(sb.length() - 1));
                
        return sb.toString();
    }
}