220111_알고리즘

Minseok-Choi·2022년 1월 11일
0

알고리즘

목록 보기
4/13
post-thumbnail

프로그래머스

객체 사용의 중요성💁

  • String.replaceAll 메서드로 정규식을 조합하면 쉽게 풀 수 있는 문제이다.
  • 문제는 객체를 사용하지 않은채로 스태틱 메서드로 하나하나 구현하고 보니 아래와 같은 상황이 벌어졌다.
// 메서드를 분리하지 않은 채로 구현하는 게 더 나을것 같은 코드...
static String recommendId(String id) {
        id = step1(id);
        id = step2(id);
        id = step3(id);
        id = step4(id);
        id = step5(id);
        id = step6(id);
        id = step7(id);
        return id;
    }
  • 어찌되었든 각 메서드의 오류는 없었기때문에, 모든 테스트케이스는 통과할 수 있었다.
  • 그 후 다른 사람 풀이를 살펴보게 되었다.
  • 결과적으로 소제목과 같이 객체의 중요성을 다시한번 느끼게 되었다😅
  • 자연스럽게 알고리즘을 풀 때 static메서드로만 메서드를 분리해서 구현하고는 했는데 이런 식으로 객체를 만들어서 처리하는 방법도 활용할 수 있도록 해야겠다.
  • 내 코드는 틀리고 이 코드가 맞다라고는 확신할 수는 없지만 아래의 코드가 훨씬 보기좋은 것은 사실이다.

아래의 코드는 프로그래머스 내의 다른 사람의 풀이를 참고했습니다.

public class NewIdRecommend {

    public static void main(String[] args) {
        String id = "...!@BaT#*..y.abcdefghijklm";
        RecommendId recommendId = new RecommendId(id)
                .step1()
                .step2()
                .step3()
                .step4()
                .step5()
                .step6()
                .step7();
        
        System.out.println(recommendId.getId());
    }
    private static class RecommendId {
        private String id;

        private RecommendId(String id) {
            this.id = id;
        }
        // 대문자를 소문자로
        private RecommendId step1() {
            id = id.toLowerCase();
            return this;
        }
		//`알파벳`,`숫자`,`-`,`_`,`.`를 제외한 모든 문자는 삭제
        private RecommendId step2() {
            id = id.replaceAll("[^a-z0-9-_.]","");
            return this;
        }
		// 마침표가 2번 연속 있는 경우 마침표 하나로 변경
        private RecommendId step3() {
            id= id.replaceAll("[.]{2,}",".");
            return this;
        }
		// 첫 문자가 마침표라면 삭제
        private RecommendId step4() {
            if(id.charAt(0) == '.') {
                id = id.substring(1);
            }
            return this;
        }
		// 문자열이 비어있다면 a 삽입
        private RecommendId step5() {
            if(id.isEmpty()) {
                id+= "a";
            }
            return this;
        }
		// 문자열 길이를 15 이하로, 마지막 문자가 마침표면 삭제
        private RecommendId step6() {
            if(id.length() > 15) {
                id = id.substring(0,15);
            }
            // 정규식으로 마침표 제거
            // id = id.replaceAll("[.]$","");
            
            //substring으로 마침표 제거
            int index = id.length()-1;
            if(id.charAt(index)=='.') {
                id =id.substring(0,index);
            }
            return this;
        }
		// 문자열이 2이하면 마지막 문자를 문자열 길이가 3이될때까지 추가
        private RecommendId step7() {
            int lastIndex = id.length()-1;
            while(id.length() < 3) {
                id += id.charAt(lastIndex);
            }
            return this;
        }

        private String getId() {
            return id;
        }
    }
profile
차곡차곡

0개의 댓글

관련 채용 정보