[Programmers] #12903 - 가운데 글자 가져오기 [Java][C++][Python]
[Programmers] #12903 - 가운데 글자 가져오기 [Java][C++][Python]
1. 아이디어
단어 s의 가운데 글자를 반환하는 문제로 홀수인 경우 1글자, 짝수인 경우 2글자를 반환해야 한다. s의 길이를 len이라고 할 때, 가운데 글자의 범위가 0-indexed에서 $\dfrac{\text{len} - 1}{2}$부터 $\dfrac{\text{len}}{2}$까지임을 이용하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(1)$ | $O(1)$ |
3. 코드
풀이 [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.