Post

[Programmers] #120913 - 잘라서 배열로 저장하기 [Java][C++][Python]

[Programmers] #120913 - 잘라서 배열로 저장하기 [Java][C++][Python]

문제 링크


1. 아이디어

문자열을 앞에서부터 길이 $n$씩 잘라 배열에 담는 문제다. 각 조각은 $n$의 배수 인덱스에서 시작하고, 길이가 $n$으로 나누어떨어지지 않으면 마지막 조각만 남은 글자 수만큼 짧다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;

class Solution {
    public String[] solution(String my_str, int n) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < my_str.length(); i += n) {
            list.add(my_str.substring(i, Math.min(i + n, my_str.length())));
        }

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

substring은 끝 인덱스가 문자열 길이를 넘으면 예외가 발생해 Math.min으로 제한했다.

1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

vector<string> solution(string my_str, int n) {
    vector<string> v;
    for (int i = 0; i < my_str.size(); i += n) {
        v.push_back(my_str.substr(i, n));
    }

    return v;
}

substr은 길이가 남은 글자 수보다 길어도 끝까지만 잘라 주므로 마지막 조각을 따로 처리하지 않았다.

1
2
def solution(my_str, n):
    return [my_str[i : i + n] for i in range(0, len(my_str), n)]

슬라이싱은 끝 인덱스가 범위를 넘어도 끝까지만 잘라 주므로 마지막 조각을 따로 처리하지 않았다.


This post is licensed under CC BY 4.0 by the author.