
在本教程中,我们需要解决给定字符串的回文子串查询。解决回文子串查询比解决 C++ 中的常规查询复杂得多。它需要更复杂的代码和逻辑。
在本教程中,我们提供了字符串 str 和 Q 个子字符串 [L...R] 查询,每个查询都有两个值 L 和 R。我们的目标编写一个程序来解决查询以确定 substring[L...R] 是否是回文。我们必须确定在 L 到 R 范围内形成的子串是否是回文来解决每个查询。例如 -
Let's input "abbbabaaaba" as our input string. The queries were [3, 13], [3, 11], [5, 8], [8, 12] It is necessary to determine whether the substring is a plaindrome A palindrome is "abaaabaaaba" (3, 13) . It is not possible to write "baaa" as a palindrome [3, 11]. As in [5, 8]: "aaab" cannot be a palindrome. There is a palindrome in "baaab" ([3, 12]).
朴素方法
这里,我们必须通过检查子字符串是否在索引范围 L 到 R 之间来查找回文因此,我们需要对所有的子串查询进行一一检查,判断是否是回文。由于有 Q 个查询,每个查询需要 0(N) 时间来回答。最坏情况下需要 0(Q.N) 时间。
立即学习“C++免费学习笔记(深入)”;
#include <bits/stdc++.h>
using namespace std;
int isPallindrome(string str){
int i, length;
int flag = 0;
length = str.length();
for(i=0;i < length ;i++){
if(str[i] != str[length-i-1]) {
flag = 1; break;
}
}
if (flag==1)
return 1;
return 0;
}
void solveAllQueries(string str, int Q, int query[][2]){
for(int i = 0; i < Q; i++){
isPallindrome(str.substr(query[i][0] - 1, query[i][1] - 1))? cout<<"Palindrome\n":cout<<"Not palindrome!\n";
}
}
int main() {
string str = "abccbeba"; int Q = 3;
int query[Q][2] = {{3, 5}, {5, 7}, {2, 1}};
solveAllQueries(str, Q, query);
return 0;
}Palindrome Palindrome Not palindrome!
使用动态规划方法来解决问题是一种有效的选择。为了解决这个问题,我们需要创建一个 DP 数组,它是一个二维数组,其中包含一个布尔值,指示 substring[i...j] 是否是 DP[i][j] 的回文。 p>
将创建此 DP 矩阵,并检查每个查询的所有 L-R 值。
#include <bits/stdc++.h>
using namespace std;
void computeDP(int DP[][50], string str){
int length = str.size();
int i, j;
for (i = 0; i < length; i++) {
for (j = 0; j < length; j++)
DP[i][j] = 0;
}
for (j = 1; j <= length; j++) {
for (i = 0; i <= length - j; i++) {
if (j <= 2) {
if (str[i] == str[i + j - 1])
DP[i][i + j - 1] = 1;
}
else if (str[i] == str[i + j - 1])
DP[i][i + j - 1] = DP[i + 1][i + j - 2];
}
}
}
void solveAllQueries(string str, int Q, int query[][2]){
int DP[50][50];
computeDP(DP, str);
for(int i = 0; i < Q; i++){
DP[query[i][0] - 1][query[i][1] - 1]?cout
<<"not palindrome!\n":cout<<"palindrome!\n";
}
}
int main() {
string str = "abccbeba"; int Q = 3;
int query[Q][2] = {{3, 5}, {5, 7}, {2, 1}};
solveAllQueries(str, Q, query);
return 0;
}palindrome! not palindrome! palindrome!
在本教程中,我们学习了如何使用 C++ 代码解决回文子串查询。我们还可以用java、python和其他语言编写这段代码。这段代码是最复杂、最冗长的代码之一。回文查询比常规子串查询更难,并且需要非常准确的逻辑。我们希望本教程对您有所帮助。
以上就是回文子字符串查询在C++中的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号