Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as a palindrome.
Examples:
Input : str = "Too hot to hoot."
Output : Sentence is palindrome.
Input : str = "Abc def ghi jklm."
Output : Sentence is not palindrome.
Note: There may be multiple spaces and/or dots between two words.
Method#1: To find if a sentence is palindrome, compare each character from left and right. If they are equal, compare until left and right of string are equal or right becomes less than left. Remember to ignore white spaces and other characters in a string.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool sentencePalindrome(string str)
{
int l = 0, h = str.length() - 1;
for ( int i = 0; i <= h; i++)
str[i] = tolower (str[i]);
while (l <= h) {
if (!(str[l] >= 'a' && str[l] <= 'z' ))
l++;
else if (!(str[h] >= 'a' && str[h] <= 'z' ))
h--;
else if (str[l] == str[h])
l++, h--;
else
return false ;
}
return true ;
}
int main()
{
string str = "Too hot to hoot." ;
if (sentencePalindrome(str))
cout << "Sentence is palindrome." ;
else
cout << "Sentence is not palindrome." ;
return 0;
}
|
Java
public class GFG
{
static boolean sentencePalindrome(String str)
{
int l = 0 ;
int h = str.length()- 1 ;
str = str.toLowerCase();
while (l <= h)
{
char getAtl = str.charAt(l);
char getAth = str.charAt(h);
if (!(getAtl >= 'a' && getAtl <= 'z' ))
l++;
else if (!(getAth >= 'a' && getAth <= 'z' ))
h--;
else if ( getAtl == getAth)
{
l++;
h--;
}
else
return false ;
}
return true ;
}
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" );
}
}
|
Python3
def sentencePalindrome(s):
l, h = 0 , len (s) - 1
s = s.lower()
while (l < = h):
if ( not (s[l] > = 'a' and s[l] < = 'z' )):
l + = 1
elif ( not (s[h] > = 'a' and s[h] < = 'z' )):
h - = 1
elif (s[l] = = s[h]):
l + = 1
h - = 1
else :
return False
return True
s = "Too hot to hoot."
if (sentencePalindrome(s)):
print ( "Sentence is palindrome." )
else :
print ( "Sentence is not palindrome." )
|
C#
using System;
public class GFG
{
static bool sentencePalindrome(String str)
{
int l = 0;
int h = str.Length - 1;
str = str.ToLower();
while (l <= h)
{
char getAtl = str[l];
char getAth = str[h];
if (!(getAtl >= 'a' &&
getAtl <= 'z' ))
l++;
else if (! (getAth >= 'a' &&
getAth <= 'z' ))
h--;
else if ( getAtl == getAth)
{
l++;
h--;
}
else
return false ;
}
return true ;
}
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" );
}
}
|
PHP
<?php
function sentencePalindrome( $str )
{
$l = 0;
$h = strlen ( $str )-1;
for ( $i = 0; $i < $h ; $i ++)
$str [ $i ] = strtolower ( $str [ $i ]);
while ( $l <= $h ) {
if (!( $str [ $l ] >= 'a' && $str [ $l ] <= 'z' ))
$l ++;
else if (!( $str [ $h ] >= 'a' && $str [ $h ] <= 'z' ))
$h --;
else if ( $str [ $l ] == $str [ $h ])
{
$l ++;
$h --;
}
else
return false;
}
return true;
}
$str = "Too hot to hoot." ;
if (sentencePalindrome( $str ))
echo "Sentence is palindrome." ;
else
echo "Sentence is not palindrome." ;
return 0;
?>
|
Javascript
<script>
function sentencePalindrome(str)
{
let l = 0;
let h = str.length-1;
str = str.toLowerCase();
while (l <= h)
{
let getAtl = str[l];
let getAth = str[h];
if (!(getAtl >= 'a' && getAtl <= 'z' ))
l++;
else if (!(getAth >= 'a' && getAth <= 'z' ))
h--;
else if ( getAtl == getAth)
{
l++;
h--;
}
else
return false ;
}
return true ;
}
let str = "Too hot to hoot." ;
if ( sentencePalindrome(str))
document.write( "Sentence is palindrome" );
else
document.write( "Sentence is not" + " " +
"palindrome" );
</script>
|
Output
Sentence is palindrome.
Time Complexity: O(N) where N is the length of the sentence
Space Complexity: O(1)
Method#2: String.erase(), reverse method simultaneously
Following are steps for our idea:
- When user input an sentence, it is further passed inside a method which will evaluate the result or the logic part.
- Method uses following logic for evaluating the result:
- It first convert all the latter in sentence to lowercase.
- It uses String.erase() method on sentence to erase the white-space in between the sentence.
- Now it uses the reverse method to reverse the sentence.
- It checked the sentence and reversed sentence and return result.
Below are implementation of above idea.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string str)
{
transform(str.begin(), str.end(), str.begin(), :: tolower );
str.erase( remove (str.begin(), str.end(), ' ' ), str.end());
string s1 = str;
string s2 = str;
reverse(s1.begin(), s1.end());
return s1 == s2;
}
int main()
{
string str = "Too hot to hoot" ;
if (isPalindrome(str))
cout << "Sentence is palindrome." ;
else
cout << "Sentence is not palindrome." ;
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static boolean sentencePalindrome(String s)
{
if (s.isEmpty())
return true ;
String str = s.toLowerCase();
str = str.replaceAll( "[^a-zA-Z0-9]" , "" );
StringBuilder revstr = new StringBuilder(str);
revstr.reverse();
String rstr = revstr.toString();
if (str.equals(rstr))
return true ;
return false ;
}
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" );
}
}
|
Python
def isPalindrome(s):
s1 = s.replace( ' ' , '')
s1 = s1.lower()
s2 = s1[:: - 1 ];
return True if s1 = = s2 else False
s = "Too hot to hoot"
if (isPalindrome(s)):
print ( "Sentence is palindrome." )
else :
print ( "Sentence is not palindrome." )
|
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
class HelloWorld {
public static bool isPalindrome( string str)
{
str = str.Replace( " " , string .Empty);
str = str.ToLower();
string s1 = str;
string s2 = str;
char [] charArray = str.ToCharArray();
Array.Reverse(charArray);
s1 = new string (charArray);
return s1 == s2;
}
static void Main() {
string str = "Too hot to hoot" ;
if (isPalindrome(str))
Console.WriteLine( "Sentence is palindrome." );
else
Console.WriteLine( "Sentence is not palindrome." );
}
}
|
Javascript
function isPalindrome(str)
{
let s1 = str.split( ' ' ).join( '' );
s1 = s1.toLowerCase();
let s2 = s1.split( '' ).reverse().join( '' );
return true ? s1 == s2 : false ;
}
let str = "Too hot to hoot" ;
if ( isPalindrome(str))
console.log( "Sentence is palindrome" );
else
console.log( "Sentence is not palindrome" );
|
Output
Sentence is palindrome.
Time Complexity: O(N)
Space Complexity: O(N)
Method: #3: Using Stack
Here we are using the stack to reverse the array and then check whether the sentence is palindrome or not.
C++
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
bool sentencePalindrome(string s)
{
string str = "" ;
for ( char c : s){
if ( isalnum (c))
str += tolower (c);
}
string reverse_str = str;
reverse(reverse_str.begin(), reverse_str.end());
return str == reverse_str;
}
int main()
{
string str = "Too hot to hoot." ;
if (sentencePalindrome(str))
cout << "Sentence is palindrome\n" ;
else
cout << "Sentence is not palindrome\n" ;
return 0;
}
|
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" );
}
}
|
Python3
def sentence_palindrome(s):
str_ = ""
for c in s:
if c.isalnum():
str_ + = c.lower()
reverse_str = str_[:: - 1 ]
return str_ = = reverse_str
if __name__ = = "__main__" :
str_ = "Too hot to hoot."
if sentence_palindrome(str_):
print ( "Sentence is palindrome" )
else :
print ( "Sentence is not palindrome" )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static bool sentencePalindrome( string s)
{
char [] str = s.ToCharArray();
Stack< char > stack = new Stack< char >();
for ( int i = 0; i < s.Length; i++){
if (Char.IsLetterOrDigit(str[i]))
stack.Push(str[i]);
}
string originalString = "" ;
string reverseString = "" ;
foreach ( char character in stack) {
reverseString += Char.ToLower(character);
}
while (stack.Count > 0){
originalString += Char.ToLower(stack.Pop());
}
return originalString.Equals(reverseString);
}
public static void Main( string [] args)
{
string str = "Too hot to hoot." ;
if (sentencePalindrome(str))
Console.WriteLine( "Sentence is palindrome" );
else
Console.WriteLine( "Sentence is not" + " " +
"palindrome" );
}
}
|
Javascript
function sentencePalindrome(s) {
let str = "" ;
for (let i = 0; i < s.length; i++) {
const c = s.charAt(i);
if (c.match(/[a-zA-Z0-9]/))
str += c.toLowerCase();
}
const reverse_str = str.split( "" ).reverse().join( "" );
return str === reverse_str;
}
const str = "Too hot to hoot." ;
if (sentencePalindrome(str))
console.log( "Sentence is palindrome" );
else
console.log( "Sentence is not palindrome" );
|
Output
Sentence is palindrome
Time Complexity: O(N)
Space Complexity: O(N)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
15 Sep, 2023
Like Article
Save Article