Escribe un programa para comprobar si una oración es un palíndromo o no. Puede ignorar los espacios en blanco y otros caracteres para considerar las oraciones como palíndromos.
Ejemplos:
Input : str = "Too hot to hoot." Output : Sentence is palindrome. Input : str = "Abc def ghi jklm." Output : Sentence is not palindrome.
Tenga en cuenta que puede haber múltiples espacios y/o puntos entre dos palabras.
Método #1: Para encontrar si una oración es palíndromo , compare cada carácter de izquierda a derecha. Si son iguales, compare hasta que la izquierda y la derecha de la string sean iguales o la derecha sea menor que la izquierda. Recuerde ignorar los espacios en blanco y otros caracteres en una string.
Implementación:
C++
// CPP program to find if a sentence is // palindrome #include <bits/stdc++.h> using namespace std; // To check sentence is palindrome or not bool sentencePalindrome(string str) { int l = 0, h = str.length() - 1; // Lowercase string for (int i = 0; i <= h; i++) str[i] = tolower(str[i]); // Compares character until they are equal while (l <= h) { // If there is another symbol in left // of sentence if (!(str[l] >= 'a' && str[l] <= 'z')) l++; // If there is another symbol in right // of sentence else if (!(str[h] >= 'a' && str[h] <= 'z')) h--; // If characters are equal else if (str[l] == str[h]) l++, h--; // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePalindrome() int main() { string str = "Too hot to hoot."; if (sentencePalindrome(str)) cout << "Sentence is palindrome."; else cout << "Sentence is not palindrome."; return 0; }
Java
// Java program to find if a sentence is // palindrome public class GFG { // To check sentence is palindrome or not static boolean sentencePalindrome(String str) { int l = 0; int h = str.length()-1; // Lowercase string str = str.toLowerCase(); // Compares character until they are equal while(l <= h) { char getAtl = str.charAt(l); char getAth = str.charAt(h); // If there is another symbol in left // of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol in right // of sentence else if(!(getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePallindrome() public static void main(String[] args) { String str = "Too hot to hoot."; if( sentencePalindrome(str)) System.out.println("Sentence is palindrome"); else System.out.println("Sentence is not" + " " + "palindrome"); } } //This code is contributed by Sumit Ghosh
Python3
# Python program to find if a sentence is # palindrome # To check sentence is palindrome or not def sentencePalindrome(s): l, h = 0, len(s) - 1 # Lowercase string s = s.lower() # Compares character until they are equal while (l <= h): # If there is another symbol in left # of sentence if (not(s[l] >= 'a' and s[l] <= 'z')): l += 1 # If there is another symbol in right # of sentence else if (not(s[h] >= 'a' and s[h] <= 'z')): h -= 1 # If characters are equal else if (s[l] == s[h]): l += 1 h -= 1 # If characters are not equal then # sentence is not palindrome else: return False # Returns true if sentence is palindrome return True # Driver program to test sentencePalindrome() s = "Too hot to hoot." if (sentencePalindrome(s)): print ("Sentence is palindrome.") else: print ("Sentence is not palindrome.") # This code is contributed by Sachin Bisht
C#
// C# program to find if a // sentence is palindrome using System; public class GFG { // To check sentence is // palindrome or not static bool sentencePalindrome(String str) { int l = 0; int h = str.Length - 1; // Lowercase string str = str.ToLower(); // Compares character until // they are equal while(l <= h) { char getAtl = str[l]; char getAth = str[h]; // If there is another symbol // in left of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol // in right of sentence else if(! (getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence // is palindrome return true; } // Driver Code public static void Main() { String str = "Too hot to hoot."; if( sentencePalindrome(str)) Console.Write("Sentence is palindrome"); else Console.Write("Sentence is not" + " " + "palindrome"); } } // This code is contributed by Nitin Mittal.
PHP
<?php // PHP program to find if a sentence is // palindrome // To check sentence is palindrome or not function sentencePalindrome($str) { $l = 0; $h = strlen($str)-1; // Lowercase string for ($i = 0; $i < $h; $i++) $str[$i] = strtolower($str[$i]); // Compares character until they are equal while ($l <= $h) { // If there is another symbol in left // of sentence if (!($str[$l] >= 'a' && $str[$l] <= 'z')) $l++; // If there is another symbol in right // of sentence else if (!($str[$h] >= 'a' && $str[$h] <= 'z')) $h--; // If characters are equal else if ($str[$l] == $str[$h]) { $l++; $h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePalindrome() $str = "Too hot to hoot."; if (sentencePalindrome($str)) echo "Sentence is palindrome."; else echo "Sentence is not palindrome."; return 0; ?>
Javascript
<script> // Javascript program to find if a sentence is // palindrome // To check sentence is palindrome or not function sentencePalindrome(str) { let l = 0; let h = str.length-1; // Lowercase string str = str.toLowerCase(); // Compares character until they are equal while(l <= h) { let getAtl = str[l]; let getAth = str[h]; // If there is another symbol in left // of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol in right // of sentence else if(!(getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePallindrome() let str = "Too hot to hoot."; if( sentencePalindrome(str)) document.write("Sentence is palindrome"); else document.write("Sentence is not" + " " + "palindrome"); //This code is contributed by avanitrachhadiya2155 </script>
Sentence is palindrome.
Complejidad de tiempo: O(N) donde N es la longitud de la oración
Complejidad de espacio: O(1)
Método #2: String.erase(), método inverso simultáneamente
Los siguientes son los pasos para nuestra idea:
- Cuando el usuario ingresa una oración, se pasa dentro de un método que evaluará el resultado o la parte lógica.
- El método utiliza la siguiente lógica para evaluar el resultado:
- Primero convierte todo lo último en oración a minúsculas.
- Utiliza el método String.erase() en la oración para borrar el espacio en blanco entre la oración.
- Ahora usa el método inverso para invertir la oración.
- Comprobó la oración y la oración invertida y devolvió el resultado.
A continuación se muestra la implementación de la idea anterior.
C++
// CPP program to find if a sentence is // palindrome #include <bits/stdc++.h> using namespace std; // To check sentence is palindrome or not bool isPalindrome(string str) { // Transforming to lowercase transform(str.begin(), str.end(), str.begin(), ::tolower); // Removing the white-spaces str.erase(remove(str.begin(), str.end(), ' '), str.end()); // Creating the copy to string string s1 = str; string s2 = str; // Reversing the string s1 reverse(s1.begin(), s1.end()); // Evaluating Result return s1 == s2; } // Driver program to test sentencePalindrome() int main() { string str = "Too hot to hoot"; if (isPalindrome(str)) cout << "Sentence is palindrome."; else cout << "Sentence is not palindrome."; return 0; }
Python
# Python program to find if a sentence is # palindrome # To check sentence is palindrome or not def isPalindrome(s): # Replacing the white-space in string s1 = s.replace(' ', '') # converting string to lowercase s1 = s1.lower() # Reversing the string s2 = s1[::-1]; # Evaluating the result return True if s1 == s2 else False # Driver program to test sentencePalindrome() s = "Too hot to hoot" if (isPalindrome(s)): print ("Sentence is palindrome.") else: print ("Sentence is not palindrome.") # This code is contributed by Sachin Bisht
Javascript
// Javascript program to find if a sentence is // palindrome // To check sentence is palindrome or not function isPalindrome(str) { // Replacing the white-space let s1 = str.split(' ').join(''); // Converting string to lower-case s1 = s1.toLowerCase(); // Reversing the string let s2 = s1.split('').reverse().join(''); // Evaluating the result return true ? s1 == s2 : false; } // Driver program to test sentencePallindrome() let str = "Too hot to hoot"; if( isPalindrome(str)) console.log("Sentence is palindrome"); else console.log("Sentence is not palindrome"); //This code is contributed by avanitrachhadiya2155
Java
import java.io.*; // Java program to find if a sentence is // palindrome public class GFG { // To check sentence is palindrome or not static boolean sentencePalindrome(String s) { if(s.isEmpty()) // if String s is empty return true return true; String str = s.toLowerCase();// convert the whole string into lower case alphabet //remove non-alphanumeric characters // replace the given string with empty string except the pattern [^a-zA-Z0-9] str = str.replaceAll("[^a-zA-Z0-9]", ""); //The reverse() method of StringBuilder is used to reverse the characters in the StringBuilder. StringBuilder revstr = new StringBuilder(str); revstr.reverse(); String rstr = revstr.toString(); if(str.equals(rstr))//if string and reversed string both are equal return true return true; return false; //else return false } // Driver program to test sentencePallindrome() public static void main(String[] args) { String str = "Too hot to hoot."; if( sentencePalindrome(str)) System.out.println("Sentence is palindrome"); else System.out.println("Sentence is not" + " " + "palindrome"); } }
Sentence is palindrome.
Complejidad de tiempo: O(N)
Complejidad de espacio: O(1)
Método: #3: Usando Stack
Aquí estamos usando la pila para invertir la array y luego verificar si Sentence es palíndromo o no.
Java
import java.io.*; import java.util.*; class GFG { static boolean sentencePalindrome(String s) { char[] str = s.toCharArray(); Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++){ if (Character.isLetterOrDigit(str[i])) stack.push(str[i]); } String string = ""; String reverse = ""; for (Character character : stack) { reverse += Character.toLowerCase(character); } while (!stack.isEmpty()){ string += Character.toLowerCase(stack.pop()); } return string.equals(reverse); } public static void main(String[] args) { String str = "Too hot to hoot."; if( sentencePalindrome(str)) System.out.println("Sentence is palindrome"); else System.out.println("Sentence is not" + " " + "palindrome"); } }
Sentence is palindrome
Complejidad temporal: O(N)
Complejidad espacial: O(N)
Este artículo es una contribución de nuclode . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA