First string from the given array whose reverse is also present in the same array | CPP implementation of the approach ; Function that returns true if s1 is equal to reverse of s2 ; If both the strings differ in length ; In case of any character mismatch ; Function to return the first word whose reverse is also present in the array ; Check every string ; Pair with every other string appearing after the current string ; If first string is equal to the reverse of the second string ; No such string exists ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isReverseEqual ( string s1 , string s2 ) { if ( s1 . length ( ) != s2 . length ( ) ) return false ; int len = s1 . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) if ( s1 [ i ] != s2 [ len - i - 1 ] ) return false ; return true ; } string getWord ( string str [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( isReverseEqual ( str [ i ] , str [ j ] ) ) return str [ i ] ; return " - 1" ; } int main ( ) { string str [ ] = { " geeks " , " for " , " skeeg " } ; cout << ( getWord ( str , 3 ) ) ; }