OneDev

[C] 백준 10988- 팰린드롬인지 확인하기 본문

자료구조&알고리즘/BOJ

[C] 백준 10988- 팰린드롬인지 확인하기

one_dev 2023. 7. 19. 21:28

문자열이 주어졌을 때, 그 문자열이 팰린드롬인지 아닌지 판별하는 함수를 정의해 풀이하였다.

시작 index는 1씩 증가, 끝 index는 1씩 감소시키며 문자들을 비교한다.

반복문이 종료될 때 까지 비교한 모든 문자들의 쌍이 같으면 팰린드롬이므로 1을 리턴하고,

하나라도 다른 쌍이 나오면 바로 반복문을 종료하고 0을 리턴한다.

이때 끝 index 를 ( 문자열의 길이 - 1 ) 로 잡아야함에 유의한다.

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>

int is_palindrome(char*);

int main() {
	char str[101];
	scanf("%s", str);

	printf("%d", is_palindrome(str));
	return 0;
}

int is_palindrome(char *str) {
	int result = 1; // 팰린드롬이면 1을, 아니라면 0을 리턴
    
	int index_front = 0; // 시작 index = 0
	int index_rear = strlen(str)-1; // 끝 index =  (문자열의 길이 - 1)
    
    /* 시작 index 가 끝 index 보다 커지면 반복문 종료 */
	while (index_front < index_rear) {
		if (str[index_front] == str[index_rear]) {
			index_front++; 
			index_rear--;
			continue;
		}
		else if (str[index_front] != str[index_rear]) {
			result = 0;
			break;
		}
	}
	return result; // 1 또는 0 을 반환
}
Comments