Check if String formed by first and last X characters of a String is a Palindrome
Last Updated :
08 Jul, 2021
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false.
Examples:
Input: str = abcdefba, X = 2
Output: true
Explanation:
First 2 characters of both string str and reversed string str are same.
Input: str = GeeksforGeeks, X = 3
Output: false
Approach: This problem can be solved by iterating over the characters of the string str. Follow the steps below to solve this problem:
- Initialize two variables say, i as 0 and n as length of str to store position of current character and length of the string str respectively.
- Iterate while i less than n and x:
- If ith character from starting and ith from the last are not equal, then print false and return.
- After completing the above steps, print true as the answer.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
void isEqualSubstring(string str, int x)
{
int n = str.length();
int i = 0;
while (i < n && i < x) {
if (str[i] != str[n - i - 1]) {
cout << "false" ;
return ;
}
i++;
}
cout << "true" ;
}
int main()
{
string str = "GeeksforGeeks" ;
int x = 3;
isEqualSubstring(str, x);
}
|
Java
import java.io.*;
class GFG {
public static void isEqualSubstring(String str, int x)
{
int n = str.length();
int i = 0 ;
while (i < n && i < x) {
if (str.charAt(i) != str.charAt(n - i - 1 )) {
System.out.println( "false" );
return ;
}
i++;
}
System.out.println( "true" );
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
int x = 3 ;
isEqualSubstring(str, x);
}
}
|
Python3
def isEqualSubstring(string, x):
n = len (string)
i = 0
while i < n and i < x:
if (string[i] ! = string[n - i - 1 ]):
print ( "false" )
return
i + = 1
print ( "true" )
return
if __name__ = = '__main__' :
string = "GeeksforGeeks"
x = 3
isEqualSubstring(string, x)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void isEqualSubstring( string str, int x)
{
int n = str.Length;
int i = 0;
while (i < n && i < x) {
if (str[i] != str[n - i - 1]) {
Console.Write( "false" );
return ;
}
i++;
}
Console.Write( "true" );
}
public static void Main()
{
string str = "GeeksforGeeks" ;
int x = 3;
isEqualSubstring(str, x);
}
}
|
Javascript
<script>
function isEqualSubstring(str, x)
{
let n = str.length;
let i = 0;
while (i < n && i < x) {
if (str[i] !== str[n - i - 1]) {
document.write( "false" );
return ;
}
i++;
}
document.write( "true" );
}
let str = "GeeksforGeeks" ;
let x = 3;
isEqualSubstring(str, x);
</script>
|
Time complexity: O(min(n, k))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...