[Programmers] #181910 - 문자열의 뒤의 n글자 [Java][C++][Python]
[Programmers] #181910 - 문자열의 뒤의 n글자 [Java][C++][Python]
1. 아이디어
뒤의 $n$글자는 my_string의 길이에서 $n$을 뺀 인덱스부터 끝까지이다. $n$이 1 이상이고 my_string의 길이 이하로 보장되므로 그 인덱스는 항상 문자열 안에 있다.
2. 코드
풀이 [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:]
음수 인덱스 슬라이스 [-n:]로 뒤에서 n개를 잘랐다. n이 1 이상이라 문제없지만 0이면 [-0:]이 전체 문자열이 된다.
This post is licensed under CC BY 4.0 by the author.