2021 네이버 웹툰 개발 챌린지 1차 코딩테스트 2번

하루히즘·2021년 7월 16일
0

설명

[문제 비공개]

풀이

import java.util.*;
import java.util.stream.*;


class Solution {
    public String[] solution(String s) {
        // 한 글자, 두 글자 문자열 예외처리.
        if(s.length() == 1) {
            return new String[]{s};
        }
        if(s.length() == 2) {
            if(s.charAt(0) == s.charAt(1)) {
                return new String[]{s.substring(0, 1), s.substring(1, 2)};
            } else {
                return new String[]{s};
            }
        }

        // 양 끝에서 동시에 비교하기 위한 포인터.
        char[] chars = s.toCharArray();
        int startIndex = 0;
        int endIndex = 1;
        int remoteStartIndex = s.length() - 1;
        int remoteEndIndex = s.length();
        int limit = s.length() % 2 == 1 ? s.length() / 2 + 1 : s.length() / 2;

        List<String> answer = new ArrayList<>();
        // 양 끝 단어들이 서로 교차되지 않을 때까지 탐색.
        while(endIndex < remoteStartIndex) {            
            // found palindrome word.
            if(Arrays.compare(chars, startIndex, endIndex, chars, remoteStartIndex, remoteEndIndex) == 0) {
                answer.add(s.substring(startIndex, endIndex));

                startIndex = endIndex;
                remoteEndIndex = remoteStartIndex;
            } 
            endIndex++;
            remoteStartIndex--;
        }

        // 아무런 단어 쌍도 찾지 못했다면 문자열을 그대로 반환.
        if(answer.size() == 0) {
            return new String[]{s};
        }

        // 역순으로 삽입.
        int listIndex = answer.size()-1;
        if(endIndex == remoteStartIndex) {
            answer.add(s.substring(endIndex, endIndex+1));
            listIndex = answer.size()-2;
        }

        while(listIndex >= 0) {
            answer.add(answer.get(listIndex--));
        }

        return answer.toArray(new String[0]);
    }
}

역시 문자열 처리 문제였는데 처음 겪어본 타입이라 좀 까다로웠다. 두 개의 포인터를 다루는 풀이로 해결했는데 시작점은 inclusive, 끝점은 exclusive 한 특성이라던가 여러가지 고려할 게 많아서 시간을 많이 잡아먹었던 것 같다. 결국 다 풀진 못했다.

profile
YUKI.N > READY?

0개의 댓글