Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated in C++
Concept
With respect of given two strings S1 and S2 of equal lengths, our task is to determine an index i such that S1[0…i] and S2[i+1…n-1] give a palindrome when concatenated together. Ithas been seen that if it is not possible to determine such an index then print -1.
Input
S1 = “pqrsu”, S2 = “wxyqp”
Output
1
S1[0..1] = “pq”, S2[2..n-1] = “ypq”
S1 + S2 = “pqyqp” indicates is a palindrome.
Input
S1 = “pqrst”, S2 = “qprqz”
Output
-1
Method
- At first, we iterate from 0 to n (length of the string) and copy ith character from S1 to another string (assume it is S).
- After that we take another temporary string temp and copy the characters of S2 from index i +1 to n.
- Finally, we verify whether the string (S + temp) is palindrome or not.
Example
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Shows function that returns true if s is palindrome
bool isPalindrome(string str){
int i = 0;
int b = str.length() - 1;
while (i< b) {
if (str[i] != str[b])
return false;
i++;
b--;
}
return true;
}
// Shows function to return the required index
int getIndex1(string S1, string S2, int n){
string S = "";
for (int i = 0; i< n; a++) {
// Used to copy the ith character in S
S = S + S1[i];
string temp = "";
// Used to copy all the character of string s2 in Temp
for (int b = i + 1; b < n; b++)
temp += S2[b];
// Verify whether the string is palindrome
if (isPalindrome(S + temp)) {
return i;
}
}
return -1;
}
// Driver code
int main(){
string S1 = "pqrsu", S2 = "wxyqp";
int n = S1.length();
cout << getIndex1(S1, S2, n);
return 0;
}
Output
1
Advertisements