[Programmers] #181906 - 접두사인지 확인하기 [Java][C++][Python]
한 문자열이 다른 문자열의 접두사로 시작하는지 확인하는 워밍업 문제.
[Programmers] #181906 - 접두사인지 확인하기 [Java][C++][Python]
1. 아이디어
접두사 여부는 두 문자열을 앞에서부터 한 글자씩 맞춰 보고 is_prefix의 모든 문자가 같은 위치의 my_string 문자와 일치하는지 확인하면 판단할 수 있다. is_prefix가 my_string보다 길면 그 시점에서 접두사가 될 수 없다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = is_prefix의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
class Solution {
public int solution(String my_string, String is_prefix) {
return my_string.startsWith(is_prefix) ? 1 : 0;
}
}
1
2
3
4
5
6
#include <bits/stdc++.h>
using namespace std;
int solution(string my_string, string is_prefix) {
return my_string.compare(0, is_prefix.size(), is_prefix) == 0;
}
string::compare(pos, count, str)는 문자열의 [pos, pos + count) 부분 문자열을 str와 사전순으로 비교해 같으면 0, 더 작으면 음수, 더 크면 양수를 반환한다. count가 남은 길이보다 크면 문자열 끝까지로 잘린다. 여기서는 pos = 0, count = is_prefix.size()로 my_string의 앞부분을 is_prefix와 비교하므로, 반환값이 0이면 그 앞부분이 is_prefix와 완전히 같다는 뜻이고 곧 접두사다. is_prefix가 my_string보다 길면 비교 구간이 my_string 전체로 잘려 길이가 모자라므로 0이 나올 수 없어 접두사가 아닌 것으로 판정된다.
1
2
def solution(my_string, is_prefix):
return int(my_string.startswith(is_prefix))
This post is licensed under CC BY 4.0 by the author.