在 C++ 中查找索引 i,使得 S1 的前缀和 S2 到 i 的后缀连接后形成回文串
概念
对于给定的两个长度相等的字符串 S1 和 S2,我们的任务是确定一个索引 i,使得 S1[0…i] 和 S2[i+1…n-1] 连接后形成回文串。如果无法确定这样的索引,则打印 -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(字符串的长度),并将 S1 中的第 i 个字符复制到另一个字符串(假设为 S)。
- 然后我们取另一个临时字符串 temp,并将 S2 中从索引 i +1 到 n 的字符复制到 temp 中。
- 最后,我们验证字符串(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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP