← Flutter & Dart

Reto de código

detectar si un texto es un palíndromo.

Reto: detectar si un texto es un palíndromo.
Un palíndromo se lee igual al derecho y al revés (ignorando mayúsculas y espacios).
Entrada: "Anita lava la tina"
Salida esperada: true
Ver solución
// Challenge: detect whether a text is a palindrome.
// A palindrome reads the same forwards and backwards (ignoring case and spaces).
// Input: "A man a plan a canal Panama"
// Expected output: true

// Solution: we normalize (lowercase, no spaces) and compare
// the text with its reversed version.
bool isPalindrome(String text) {
  final cleaned = text.toLowerCase().replaceAll(RegExp(r'[^a-z0-9]'), '');
  final reversed = cleaned.split('').reversed.join('');
  return cleaned == reversed;
}

void main() {
  print(isPalindrome('level')); // true
  print(isPalindrome('A man a plan a canal Panama')); // true
  print(isPalindrome('Flutter')); // false
  print(isPalindrome('')); // true (an empty string is a palindrome)

  // Explanation:
  // 1) toLowerCase() ignores uppercase/lowercase.
  // 2) replaceAll with the regular expression removes everything that is not
  //    a letter or a number (spaces, accents depending on the case, symbols).
  // 3) We compare the cleaned text with its reversed version.
}