BACKWARD AND FORWARD STRING

BACKWARD AND FORWARD STRING

PROBLEM STATEMENT :

Consider one string as input. You have to check whether the strings obtained from the input string with single backward and single forward shifts are the same or not. If they are the same, then print 1, otherwise, print 0.

Hint:
Backward shift: A single circular rotation of the string in which the first character becomes the last character and all the other characters are shifted one index to the left. For example, “abcde” becomes “bcdea” after one backward shift.
Forward shift: A single circular rotation of the string in which the last character becomes the first character and all the other characters are shifted to the right. For example, “abcde” becomes “eabcd” after one forward shift.

Constraints:
String str should not allow space, special characters, and numbers.
String str should only be in the English language.
1 <= len(str) <=1000


Example Input/Output 1: 
Input: () 
sfdlmnop 
Output: 0

Explanation: 

In the first example, the string is "sfdlmnop" 
Forward shift: fdlmnops 
Backward shift: psfdlmno 
Both the strings above are not equal so the output is 0.


Example Input/Output 2: 
Input: () 
abab 
Output: 1




                    


            1)    LEARN THRICE 

                                👇 

            2)    THINK TWICE

                                👇 

            3)    APPLY ONCE




SOLUTION :

C (Programming Language)


      

#include <stdio.h> #include<string.h> int isEqual(char str[]) { int i,l=strlen(str); if(str[l-1]!=str[1]) return 0; for(i=1;str[i+1]!='\0';++i) { if(str[i-1]!=str[i+1]) return 0; } if(str[l-2]!=str[0]) return 0; return 1; } int main() { char str[1001]; scanf("%s",str); int res=isEqual(str); printf("%d",res); return 0; }



C++ (CPP)

       

#include <bits/stdc++.h> using namespace std; int main(int argc, char** argv) { string s,forward,backward; cin>>s; int l=s.size(); forward=s.substr(1)+s[0]; backward=s[l-1]+s.substr(0,l-1); cout<<(forward==backward); return 0; }



JAVA

       

import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String s=sc.nextLine().trim(),forward,backward; int l=s.length(); forward=s.substring(1)+s.charAt(0); backward=s.charAt(l-1)+s.substring(0,l-1); System.out.println(forward.compareTo(backward)==0?1:0); } }



PYTHON

       

s=input().strip() forward=s[1:]+s[0] backward=s[-1]+s[:-1] print(int(forward==backward))



Never Stop Learning !!


Comments

Popular posts from this blog

DP (1) - Count number of ways to cover a distance

Zero Insert After K Times One

Left Number Twice Right