본문 바로가기
개발로그/알고리즘

프로그래머스 Lv.0 잘라서 배열로 저장하기

by 쩜징 2023. 7. 26.

프로그래머스 Lv.0 잘라서 배열로 저장하기


문자열 my_str과 n이 매개변수로 주어진다.

my_str을 길이 n씩 잘라서 저장한 배열을 return하라.

 

my_str은 알파벳 소문자, 대문자, 숫자로 이루어져 있다.

 

my_str n result
"abc1Addfggg4556b" 6 ["abc1Ad", "dfggg4", "556b"]
"abcdef123" 3 ["abc", "def", "123"]

** 풀이 방법

 

my_str을 n으로 나눠서 자를때

my_str의 길이/n번 자르게 되는데

my_str의 길이/n이 나누어 떨어지지 않는다면

남아있는 문자열이 있는 것이므로

my_str의 길이/n+1번 자르게 된다.

int chk = (my_str.length()/n == 0? my_str.length()/n : my_str.length()/n+1);

 

for문을 돌려서 i는 i+n씩 증가하도록 설정한다.

for (int i=0; i<my_str.length(); i+=n) {...}

 

왼쪽부터 n개씩 문자열을 자를건데 몇 가지 조건이 있다.

1) chk번 문자열을 자를 것!

2) 자르는 범위가 주어진 문자열보다 커지게 되면 남아있는 길이만큼 저장할 것!

이 조건 외에 나머지는 n개씩 잘라주면 된다.

for (int i=0; i<my_str.length(); i+=n) {
    if (cnt == chk) {
        break;
    } else if (tmp>=my_str.length()) {
        answer.add(my_str.substring(i));
        cnt++;
        break;
    } else {
         answer.add(my_str.substring(i,tmp));
         cnt++; tmp += n;
    } 
}

 

<> 전체 코드 </>

import java.util.*;
class Solution {
    public List<String> solution(String my_str, int n) {
        List<String> answer = new ArrayList<>();
        int cnt = 0;
        int tmp = n;
        int chk = ( my_str.length()/n == 0 ? my_str.length()/n : my_str.length()/n+1);
        for (int i=0; i<my_str.length(); i+=n) {
            if (cnt == chk) {
                break;
            } else if (tmp>=my_str.length()) {
                answer.add(my_str.substring(i));
                cnt++;
                break;
            } else {
                 answer.add(my_str.substring(i,tmp));
                 cnt++; tmp += n;
            } 
        }
        return answer;
    }
}

 

반응형

댓글