Post

[Programmers] #181904 - 세로 읽기 [Java][C++][Python]

[Programmers] #181904 - 세로 읽기 [Java][C++][Python]

문제 링크


1. 아이디어

문자열을 한 줄에 $m$글자씩 적었을 때 $c$번째 열을 위에서 아래로 읽는 문제다. 위아래로 이웃한 칸의 인덱스는 $m$ 차이가 난다. 열 번호를 1부터 세므로 $c$번째 열의 첫 칸은 인덱스 $c - 1$이고, 거기서 $m$씩 건너뛰며 읽으면 된다.


2. 코드

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

1
2
3
4
5
6
7
8
9
10
class Solution {
    public String solution(String my_string, int m, int c) {
        StringBuilder sb = new StringBuilder();
        for (int i = c - 1; i < my_string.length(); i += m) {
            sb.append(my_string.charAt(i));
        }

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

string solution(string my_string, int m, int c) {
    string s;
    for (int i = c - 1; i < my_string.size(); i += m) {
        s += my_string[i];
    }

    return s;
}
1
2
def solution(my_string, m, c):
    return my_string[c - 1 :: m]

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