컨셉
동일한 길이의 주어진 두 문자열 S1과 S2와 관련하여 우리의 임무는 S1[0…i]와 S2[i+1…n-1]이 함께 연결될 때 회문을 제공하도록 인덱스 i를 결정하는 것입니다. 그러한 색인을 결정할 수 없으면 -1을 인쇄하는 것으로 나타났습니다.
입력
S1 = “pqrsu”, S2 = “wxyqp”
출력
1
S1[0..1] ="pq", S2[2..n-1] ="ypq"
S1 + S2 ="pqyqp"는 회문임을 나타냅니다.
입력
S1 = “pqrst”, S2 = “qprqz”
출력
-1
방법
- 처음에는 0에서 n(문자열 길이)까지 반복하고 i번째 문자를 S1에서 다른 문자열로 복사합니다(S라고 가정).
- 그 후에 다른 임시 문자열 temp를 가져와 인덱스 i +1에서 n으로 S2의 문자를 복사합니다.
- 마지막으로 문자열(S + temp)이 회문인지 여부를 확인합니다.
예시
// 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;
} 출력
1