티스토리 뷰

300x250

솔루션1

public static String[] solution(String my_str, int n) {
    String[] answer   = new String[(my_str.length() + n - 1) / n]; // 문자열 길이에서 n만큼 나눈 몫으로 배열 생성
    String addData    = "";
    int    cnt        = 0;
    int    firstSubIndex = 0;
    int    lastSubIndex  = n;
    int    increase      = n;
    for(int i = 0; i < my_str.length(); i++){ //한글자씩 처리
        int lastNum = my_str.length()-1;
        if(i == (increase-1) || i == lastNum){ //자르려는 길이일땐 배열에 담고 마지막 일땐 마지막 만큼만
            addData     += my_str.substring(firstSubIndex,(lastNum == i?my_str.length():lastSubIndex));
            answer[cnt] = addData;
            addData     = ""; // 원하는 만큼 담고 초기화
            cnt++;         //다음 배열에 담기위해서 증가.
            firstSubIndex = i+1;
            lastSubIndex  = n+n;
            increase = increase + increase;
        }
    }
    return answer;
}

 

솔루션2(해당 솔루션은 프로그래머스 내에서도 별로 없다 다만 JAVA8?이후부터 제공된다)

public static String[] solution2(String my_str, int n) {
    String[] answer = my_str.split(my_str,n);
    return answer;
}
728x90

'알고리즘 > 프로그래머스' 카테고리의 다른 글

외계인 사전.  (0) 2023.05.31
다항식 더하기  (0) 2023.05.31
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함