문제는 어렵지않다. is_prefix가 접두사인지 아닌지 확인 하면 되는 문제이다.
알고리즘:
def solution(my_string, is_prefix):
answer = 0
count = 0
for i in range(len(is_prefix)):
if is_prefix[i] == my_string[i]:
count +=1
if count == len(is_prefix):
answer = 1
else:
answer = 0
return answer
처음에는 is_prefix의 문자열 길이만큼 my_string과 is_prefix의 문자를 하나씩 비교하면서 count가
is_prefix길이랑 같으면 answer=1 아니면 answer = 0으로 출력하려 했다.
하지만is_prefix의 길이가 my_string의 길이보다 길수도 있는 경우를 배제했다. 따라서 길이비교에서
인덱스 오류를 방지하는 코드를 적어주면 된다.
def solution(my_string, is_prefix):
count = 0
if len(is_prefix) > len(my_string):
return 0
for i in range(len(is_prefix)):
if is_prefix[i] == my_string[i]:
count +=1
if count == len(is_prefix):
return 1
else:
return 0
위의 코드처럼 문자열을 비교해서 is_prefix가 더 긴 경우 return 0을 해줘야한다.
하지만 파이썬에는 접두사를 비교할수있는 startswith라는 함수가 있다.
def solution(my_string, is_prefix):
answer = 0
if my_string.startswith(is_prefix):
answer = 1
else:
answer = 0
return answer
이런식으로 코드를 작성할수도 있다
'코딩테스트' 카테고리의 다른 글
프로그래머스 레벨0 진료순서 정하기 (0) | 2024.06.09 |
---|---|
프로그래머스 레벨0 문자열 계산하기 (0) | 2024.05.18 |
프로그래머스 레벨 0 소인수분해 (0) | 2024.04.14 |
프로그래머스 레벨0 삼각형의 완성조건 (2) (0) | 2024.04.13 |
프로그래머스 레벨0 문자 반복 출력하기 (2) | 2024.04.12 |