본문 바로가기

Programming language/C++

[C++] palindrome 예제 소스코드

이 프로그램은 사용자에게 문자열을 입력하라는 메시지를 표시한 다음 입력한 문자열이 공백과 대소문자를 무시하고 앞뒤로 똑같이 읽는 팔린드롬(palindrome) 문자열인지 확인합니다.

 

소스코드

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// Function to check if a string is a palindrome
bool isPalindrome(string str) {
    // Remove spaces and convert to lowercase
    str.erase(remove_if(str.begin(), str.end(), ::isspace), str.end());
    transform(str.begin(), str.end(), str.begin(), ::tolower);

    int left = 0;
    int right = str.length() - 1;

    while (left < right) {
        if (str[left] != str[right]) {
            return false; // Not a palindrome
        }
        left++;
        right--;
    }

    return true; // It's a palindrome
}

int main() {
    string input;

    cout << "Palindrome Checker" << endl;
    cout << "Enter a string: ";
    getline(cin, input);

    if (isPalindrome(input)) {
        cout << "Yes, it's a palindrome!" << endl;
    } else {
        cout << "No, it's not a palindrome." << endl;
    }

    return 0;
}

출력 결과

Palindrome Checker
Enter a string: A man a plan a canal Panama
Yes, it's a palindrome!

이 예제에서 사용자는 공백과 대소문자를 무시할 때 팔린드롬이 되는 문자열 "A man a plan a canal Panama"를 입력했으므로 프로그램에서 팔린드롬으로 올바르게 식별합니다.