C++ 检查字符串是否在两端有可逆相等的子字符串

C++ 检查字符串是否在两端有可逆相等的子字符串

在这个问题中,我们需要从字符串的开头和结尾找到最长的可逆相等子字符串。

这个问题与寻找回文字符串非常相似。我们可以从开始遍历字符串,直到字符串的开头和结尾的字符匹配。

问题陈述 - 给定一个包含N个字符的字符串str。我们需要检查字符串在开始和结尾是否含有可逆相等的子字符串。如果按照给定条件找到了子字符串,则输出最长的子字符串。否则,在输出中打印’false’。

示例

输入

str = "tutorialsotut"

输出

‘tut’

说明 − ‘tut’ 在开头出现,并且‘tut’的逆序在末尾出现。

输入

str = ‘abcytrfghgyuyjcba’

输出

‘abc’

解释 - 在给定的字符串中,开头有’abc’,结尾有’cab’。

输入

str = ‘vdfdvcf’

输出

False

解释 − 字符串中没有任何可逆子串。因此,打印false。

方法1

在这种方法中,我们将从字符串的起始位置开始遍历。我们将从起始位置和末尾位置匹配字符串的字符。当我们找到不匹配的字符时,我们将停止迭代。

步骤

步骤1 − 用0初始化变量‘p’,用字符串长度减1初始化变量‘q’。

步骤2 − 同样,用一个空字符串初始化变量‘res’,用来存储所需的字符串。

步骤3 − 使用循环进行迭代,直到‘q’大于或等于零。

步骤4 − 如果s[p]和s[q]字符相等,将它们附加到‘res’字符串中。同时,增加p的值1,并将q减1。

步骤5 − 如果s[p]和s[q]不相同,使用‘break’关键字中断循环。

步骤6 − 如果‘res’字符串的大小等于零,则打印false。否则,打印‘res’字符串。

示例

#include <bits/stdc++.h>
using namespace std;
// Check if the string has reversible equal substring at the start and end of a given string
void ReversibleEqual(string s) {
    // Initialize the length and pointer variables
    int len = s.size();
    int p = 0;
    int q = len - 1;
    string res = "";
    // Iterate over the string
    while (q >= 0) {
        // If characters at index p and q are the same
        if (s[p] == s[q]) {
            // append a character to 'res', and modify p and q value
            res += s[p];
            p++;
            q--;
        } else {
            break;
        }
    }
    // If the substring is not present, print False
    if (res.size() == 0)
        cout << "False";
    // print true
    else {
        cout << "True \n"
             << res;
    }
}
int main() {
    string str = "tutorialsotut";
    ReversibleEqual(str);
    return 0;
}

输出

True 
tuto

时间复杂度 − O(N),因为我们使用循环来迭代字符串

空间复杂度 − O(N),因为我们存储了可逆字符串。

程序员可以通过直接打印每个字符而不是将其附加到“res”字符串中来优化上述解决方案。解决方案的方法非常类似于检查字符串是否是回文。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程