We are given a string, we need to check whether the first and last characters of the string str are equal or not. Case sensitivity is to be considered.
Examples :
Input : university
Output : Not Equal
Explanation: In the string "university", the first character is 'u'
and the last character is 'y', as they are not equal, "Not Equal" is the output.
Input : racecar
Output : Equal
Explanation: In the string "racecar", the first character is 'r'
and the last character is 'r', as they are equal, "Equal" is the output.
Implementation:
C++
#include<iostream>
using namespace std;
int areCornerEqual(string s)
{
int n = s.length();
if (n < 2)
return -1;
if (s[0] == s[n - 1])
return 1;
else
return 0;
}
int main()
{
string s = "GfG" ;
int res = areCornerEqual(s);
if (res == -1)
cout<< "Invalid Input" ;
else if (res == 1)
cout<< "Equal" ;
else
cout<< "Not Equal" ;
}
|
Java
class GFG {
public static int areCornerEqual(String s)
{
int n = s.length();
if (n < 2 )
return - 1 ;
if (s.charAt( 0 ) == s.charAt(n- 1 ))
return 1 ;
else
return 0 ;
}
public static void main(String[] args)
{
String s = "GfG" ;
int res = areCornerEqual(s);
if (res == - 1 )
System.out.println( "Invalid Input" );
else if (res == 1 )
System.out.println( "Equal" );
else
System.out.println( "Not Equal" );
}
}
|
Python3
st = "GfG"
if (st[ 0 ] = = st[ - 1 ]):
print ( "Equal" )
else :
print ( "Not Equal" )
|
C#
using System;
class GFG
{
public static int areCornerEqual(String s)
{
int n = s.Length;
if (n < 2)
return -1;
if (s[0] == s[n - 1])
return 1;
else
return 0;
}
static public void Main ()
{
String s = "GfG" ;
int res = areCornerEqual(s);
if (res == -1)
Console.WriteLine( "Invalid Input" );
else if (res == 1)
Console.WriteLine( "Equal" );
else
Console.WriteLine( "Not Equal" );
}
}
.
|
PHP
<?php
function areCornerEqual( $s )
{
$n = strlen ( $s );
if ( $n < 2)
return -1;
if ( $s [0] == $s [ $n - 1])
return 1;
else
return 0;
}
$s = "GfG" ;
$res = areCornerEqual( $s );
if ( $res == -1)
echo ( "Invalid Input" );
else if ( $res == 1)
echo ( "Equal" );
else
echo ( "Not Equal" );
?>
|
Javascript
<script>
function areCornerEqual(s)
{
let n = s.length;
if (n < 2)
return -1;
if (s[0] == s[n - 1])
return 1;
else
return 0;
}
let s = "GfG" ;
let res = areCornerEqual(s);
if (res == -1)
document.write( "Invalid Input" );
else if (res == 1)
document.write( "Equal" );
else
document.write( "Not Equal" );
</script>
|
Time Complexity : O(1)
Auxiliary Space : O(1)
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 :
20 Feb, 2023
Like Article
Save Article