[Programmers] #181910 - 문자열의 뒤의 n글자 [Java][C++][Python]
문자열 뒤쪽 n글자를 잘라 반환하는 워밍업 문제.
[Programmers] #181910 - 문자열의 뒤의 n글자 [Java][C++][Python]
1. 아이디어
my_string의 뒤 n글자를 반환하는 문제다. 전체 길이에서 n을 뺀 인덱스부터 끝까지의 부분 문자열이 곧 답이므로, 그 구간을 그대로 잘라 반환하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = 잘라낼 길이, 파라미터 n)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
class Solution {
public String solution(String my_string, int n) {
return my_string.substring(my_string.length() - n);
}
}
1
2
3
4
5
6
#include <bits/stdc++.h>
using namespace std;
string solution(string my_string, int n) {
return my_string.substr(my_string.size() - n);
}
1
2
def solution(my_string, n):
return my_string[-n:]
This post is licensed under CC BY 4.0 by the author.