[Programmers] #12903 - 가운데 글자 가져오기 [Java][C++][Python]
[Programmers] #12903 - 가운데 글자 가져오기 [Java][C++][Python]
1. 아이디어
단어 $s$의 가운데 글자를 구하는 문제로, 길이가 홀수면 한 글자, 짝수면 두 글자다. $s$의 길이를 $n$이라 하면 가운데가 시작하는 인덱스(0부터)는 $n = 2k + 1$일 때 $k$, $n = 2k$일 때 $k - 1$인데, 둘 다 $\lfloor (n - 1) / 2 \rfloor$와 같으므로 홀짝을 나누지 않고 이 위치부터 홀수면 한 글자, 짝수면 두 글자를 자르면 된다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
class Solution {
public String solution(String s) {
int len = s.length();
return s.substring((len - 1) / 2, len / 2 + 1);
}
}
1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;
string solution(string s) {
int len = s.size();
return s.substr((len - 1) / 2, 2 - len % 2);
}
1
2
3
def solution(s):
length = len(s)
return s[(length - 1) // 2 : length // 2 + 1]
This post is licensed under CC BY 4.0 by the author.