easystringtwo-pointer

Palindrome Check

Read a string, print "true" if it is a palindrome (case-insensitive, alphanumerics only), else "false".

Problem

Statement

A palindrome reads the same forwards and backwards. Real-world variants strip whitespace and punctuation and lowercase everything first — "A man, a plan, a canal: Panama" is a palindrome by that definition.

Standard O(n) approach: filter and lowercase the string, then two-pointer compare from ends inward. Alternative: reverse and compare — same complexity, simpler code, slightly more allocation.

Worked cases

Examples

Input
A man, a plan, a canal: Panama
Output
true
Input
race a car
Output
false
Input
Output
true
NoteThe empty string is trivially a palindrome.
Bounds

Constraints

  • 0 ≤ input length ≤ 10^5
Reference

Sample solutions

Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.

Python
s = ''.join(c.lower() for c in input() if c.isalnum())
print('true' if s == s[::-1] else 'false')
Java
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        String s = new Scanner(System.in).hasNextLine() ? new Scanner(System.in).nextLine() : "";
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) if (Character.isLetterOrDigit(c)) sb.append(Character.toLowerCase(c));
        String f = sb.toString();
        String r = sb.reverse().toString();
        System.out.println(f.equals(r) ? "true" : "false");
    }
}
C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s; getline(cin, s);
    string f;
    for (char c : s) if (isalnum((unsigned char)c)) f.push_back(tolower((unsigned char)c));
    string r = f; reverse(r.begin(), r.end());
    cout << (f == r ? "true" : "false") << "\n";
}
Also try