Palindromic String | Basics of Input/Output
Problem Statement :
You have been given a String S. You need to find and print whether this string is a palindrome or not. If yes, print "YES" (without quotes), else print "NO" (without quotes).
Problem Link:
https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/palindrome-check-2/
Input Format :
The first and only line of input contains the String S. The String shall consist of lowercase English alphabets only.
The first and only line of input contains the String S. The String shall consist of lowercase English alphabets only.
Output Format :
Print the required answer on a single line.
Print the required answer on a single line.
Constraints :
String S consists of lowercase English Alphabets only.
Solution :
//Code here
#include <iostream>
using namespace std;
int main()
{
char str[100];
cin>>str; // input string
int i,j; // looping variables
int len; // to store string length
for(len=0;str[len]!='\0';len++); // counting string length
int flag=1; // flag variable
for(i=0,j=len-1;i<len/2;i++,j--)
{
if(str[i]!=str[j]) // if adjacent characters are not same
{
flag=0; break; //string not palindrome, flag 0, break loop
}
}
if(flag==1)
cout<<"YES";
else
cout<<"NO";
return 0;
}
| Code Snippet |
| Submission |
Solution Explained :
We used a character array str of size 100 ( as max size of string is 100 ). Then we declare two looping variables i and j. We used a integer len to store length of string str. We used a loop of len from len=0 to str[len]!='/0' to count the length of string str ( Line No.13). Then we started a loop of i and j, i pointing to 1st character and j pointing to last character, for each iteration we checked if characters pointed by i-j are same or not, if same we i++ and j--. Likewise we compare all the adjacent characters of string str. If at any instance adjacent characters are not same, we make flag=0 and break the loop. Finally we check for the value of flag, if it is 1 i.e., unchanged it implies all adjacent characters are same and string is Palindrome, if value of flag is other, that means string is not Palindrome.
This completes our Program.
Do comment your response plz.
FOR ANY QUERY REGARDING SOLUTION
free feel to contact
Rahul Badgujar
WhatsApp : +917775919753
Email: rahulrb15899@gmail.com
Comments
Post a Comment