给定字符串str ,任务是检查是否可以将给定字符串S拆分为三个回文子串。如果有多个答案是可能的,则打印其中切割索引最少的那个。如果不存在这种可能的分区,则打印“-1” 。
例子:
Input: str = “aabbcdc”
Output: aa bb cdc
Explanation:
Only one possible partition exists {“aa”, “bb”, “cdc”}.
Input: str = “ababbcb”
Output: a bab bcb
Explanation: Possible splits are {“aba”, “b”, “bcb”} and {“a”, “bab”, “bcb”}.
Since, {“a”, “bab”, “bcb”} has splits at earlier indices, it is the required answer.
处理方法:按照以下步骤解决问题:
- 生成字符串的所有可能的子字符串并检查给定的子串是否是回文的。
- 如果存在任何子字符串,则将子字符串的最后一个索引存储在向量startPal 中,其中startPal将存储从 0 索引开始并以存储值结束的第一个回文。
- 与第一步类似,从给定字符串str的最后一个索引生成所有子字符串,并检查给定子字符串是否为回文。如果任何子字符串作为子字符串存在,则将子字符串的最后一个索引存储在向量lastPal 中,其中lastPal将存储从存储的值开始并在给定字符串str 的第(N – 1)个索引处结束的第三个回文。
- 反转向量lastPal以获得最早的切割。
- 现在,迭代两个嵌套循环,外环拾取结束从startPal和内循环索引第一回文主从lastPal第三回文起始索引。如果startPal的值大于lastPal值较小然后将其存储在双形式middlePal矢量。
- 现在遍历向量middlePal并检查第一个回文的结束索引和第三个回文的起始索引之间的子串是否为回文。如果发现为真,则第一个回文 = s.substr(0, middlePal[i].first) ,第三个回文 = s.substr(middlePal[i].second, N – middlePal[i].second)和其余字符串将是第三个字符串。
- 如果所有三个回文字符串都存在,则打印该字符串,否则打印“-1” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if a string
// is palindrome or not
bool isPalindrome(string x)
{
// Copy the string x to y
string y = x;
// Reverse the string y
reverse(y.begin(), y.end());
if (x == y) {
// If string x equals y
return true;
}
return false;
}
// Function to find three palindromes
// from the given string with earliest
// possible cuts
void Palindromes(string S, int N)
{
// Stores index of palindrome
// starting from left & right
vector startPal, lastPal;
string start;
// Store the indices for possible
// palindromes from left
for (int i = 0;
i < S.length() - 2; i++) {
// Push the current character
start.push_back(S[i]);
// Check for palindrome
if (isPalindrome(start)) {
// Insert the current index
startPal.push_back(i);
}
}
string last;
// Stores the indexes for possible
// palindromes from right
for (int j = S.length() - 1;
j >= 2; j--) {
// Push the current character
last.push_back(S[j]);
// Check palindromic
if (isPalindrome(last)) {
// Insert the current index
lastPal.push_back(j);
}
}
// Sort the indexes for palindromes
// from right in ascending order
reverse(lastPal.begin(),
lastPal.end());
vector > middlePal;
for (int i = 0;
i < startPal.size(); i++) {
for (int j = 0;
j < lastPal.size(); j++) {
// If the value of startPal
// < lastPal value then
// store it in middlePal
if (startPal[i] < lastPal[j]) {
// Insert the current pair
middlePal.push_back(
{ startPal[i],
lastPal[j] });
}
}
}
string res1, res2, res3;
int flag = 0;
// Traverse over the middlePal
for (int i = 0;
i < middlePal.size(); i++) {
int x = middlePal[i].first;
int y = middlePal[i].second;
string middle;
for (int k = x + 1; k < y; k++) {
middle.push_back(S[k]);
}
// Check if the middle part
// is palindrome
if (isPalindrome(middle)) {
flag = 1;
res1 = S.substr(0, x + 1);
res2 = middle;
res3 = S.substr(y, N - y);
break;
}
}
// Print the three palindromic
if (flag == 1) {
cout << res1 << " "
<< res2 << " "
<< res3;
}
// Otherwise
else
cout << "-1";
}
// Driver Code
int main()
{
// Given string str
string str = "ababbcb";
int N = str.length();
// Function Call
Palindromes(str, N);
return 0;
}
Java
// Java program for the
// above approach
import java.util.*;
class GFG{
static class pair
{
int first, second;
public pair(int first,
int second)
{
this.first = first;
this.second = second;
}
}
static String reverse(String input)
{
char[] a = input.toCharArray();
int l, r = a.length - 1;
for (l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
// Function to check if a String
// is palindrome or not
static boolean isPalindrome(String x)
{
// Copy the String x to y
String y = x;
// Reverse the String y
y = reverse(y);
if (x.equals(y))
{
// If String x equals y
return true;
}
return false;
}
// Function to find three palindromes
// from the given String with earliest
// possible cuts
static void Palindromes(String S,
int N)
{
// Stores index of palindrome
// starting from left & right
Vector startPal =
new Vector<>();
Vector lastPal =
new Vector<>();
String start = "";
// Store the indices for possible
// palindromes from left
for (int i = 0;
i < S.length() - 2; i++)
{
// Push the current character
start += S.charAt(i);
// Check for palindrome
if (isPalindrome(start))
{
// Insert the current index
startPal.add(i);
}
}
String last = "";
// Stores the indexes for possible
// palindromes from right
for (int j = S.length() - 1;
j >= 2; j--)
{
// Push the current character
last += S.charAt(j);
// Check palindromic
if (isPalindrome(last))
{
// Insert the current index
lastPal.add(j);
}
}
// Sort the indexes for palindromes
// from right in ascending order
Collections.reverse(lastPal);
Vector middlePal =
new Vector<>();
for (int i = 0;
i < startPal.size(); i++)
{
for (int j = 0;
j < lastPal.size(); j++)
{
// If the value of startPal
// < lastPal value then
// store it in middlePal
if (startPal.get(i) <
lastPal.get(j))
{
// Insert the current pair
middlePal.add(new pair(startPal.get(i),
lastPal.get(j)));
}
}
}
String res1 = "",
res2 = "", res3 = "";
int flag = 0;
// Traverse over the middlePal
for (int i = 0;
i < middlePal.size(); i++)
{
int x = middlePal.get(i).first;
int y = middlePal.get(i).second;
String middle = "";
for (int k = x + 1; k < y; k++)
{
middle += S.charAt(k);
}
// Check if the middle part
// is palindrome
if (isPalindrome(middle))
{
flag = 1;
res1 = S.substring(0, x + 1);
res2 = middle;
res3 = S.substring(y, N);
break;
}
}
// Print the three palindromic
if (flag == 1)
{
System.out.print(res1 + " " +
res2 + " " + res3);
}
// Otherwise
else
System.out.print("-1");
}
// Driver Code
public static void main(String[] args)
{
// Given String str
String str = "ababbcb";
int N = str.length();
// Function Call
Palindromes(str, N);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program for the above approach
# Function to check if a strring
# is palindrome or not
def isPalindrome(x):
# Copy the x to y
y = x
# Reverse the y
y = y[::-1]
if (x == y):
# If x equals y
return True
return False
# Function to find three palindromes
# from the given with earliest
# possible cuts
def Palindromes(S, N):
# Stores index of palindrome
# starting from left & right
startPal, lastPal = [], []
start = []
# Store the indices for possible
# palindromes from left
for i in range(len(S) - 2):
# Push the current character
start.append(S[i])
# Check for palindrome
if (isPalindrome(start)):
# Insert the current index
startPal.append(i)
last = []
# Stores the indexes for possible
# palindromes from right
for j in range(len(S) - 1, 1, -1):
# Push the current character
last.append(S[j])
# Check palindromic
if (isPalindrome(last)):
# Insert the current index
lastPal.append(j)
# Sort the indexes for palindromes
# from right in ascending order
lastPal = lastPal[::-1]
middlePal = []
for i in range(len(startPal)):
for j in range(len(lastPal)):
# If the value of startPal
# < lastPal value then
# store it in middlePal
if (startPal[i] < lastPal[j]):
# Insert the current pair
middlePal.append([startPal[i],
lastPal[j]])
res1, res2, res3 = "", "", ""
flag = 0
# Traverse over the middlePal
for i in range(len(middlePal)):
x = middlePal[i][0]
y = middlePal[i][1]
#print(x,y)
middle = ""
for k in range(x + 1, y):
middle += (S[k])
# Check if the middle part
# is palindrome
if (isPalindrome(middle)):
flag = 1
res1 = S[0 : x + 1]
res2 = middle
res3 = S[y : N]
#print(S,x,y,N)
break
# Print the three palindromic
if (flag == 1):
print(res1, res2, res3)
# Otherwise
else:
print("-1")
# Driver Code
if __name__ == '__main__':
# Given strr
strr = "ababbcb"
N = len(strr)
# Function call
Palindromes(strr, N)
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
public class pair
{
public int first, second;
public pair(int first,
int second)
{
this.first = first;
this.second = second;
}
}
static String reverse(String input)
{
char[] a = input.ToCharArray();
int l, r = a.Length - 1;
for(l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.Join("",a);
}
// Function to check if a String
// is palindrome or not
static bool isPalindrome(String x)
{
// Copy the String x to y
String y = x;
// Reverse the String y
y = reverse(y);
if (x.Equals(y))
{
// If String x equals y
return true;
}
return false;
}
// Function to find three palindromes
// from the given String with earliest
// possible cuts
static void Palindromes(String S,
int N)
{
// Stores index of palindrome
// starting from left & right
List startPal = new List();
List lastPal = new List();
String start = "";
// Store the indices for possible
// palindromes from left
for(int i = 0;
i < S.Length - 2; i++)
{
// Push the current character
start += S[i];
// Check for palindrome
if (isPalindrome(start))
{
// Insert the current index
startPal.Add(i);
}
}
String last = "";
// Stores the indexes for possible
// palindromes from right
for(int j = S.Length - 1;
j >= 2; j--)
{
// Push the current character
last += S[j];
// Check palindromic
if (isPalindrome(last))
{
// Insert the current index
lastPal.Add(j);
}
}
// Sort the indexes for palindromes
// from right in ascending order
lastPal.Reverse();
List middlePal = new List();
for(int i = 0;
i < startPal.Count; i++)
{
for(int j = 0;
j < lastPal.Count; j++)
{
// If the value of startPal
// < lastPal value then
// store it in middlePal
if (startPal[i] < lastPal[j])
{
// Insert the current pair
middlePal.Add(new pair(startPal[i],
lastPal[j]));
}
}
}
String res1 = "", res2 = "",
res3 = "";
int flag = 0;
// Traverse over the middlePal
for(int i = 0;
i < middlePal.Count; i++)
{
int x = middlePal[i].first;
int y = middlePal[i].second;
String middle = "";
for(int k = x + 1; k < y; k++)
{
middle += S[k];
}
// Check if the middle part
// is palindrome
if (isPalindrome(middle))
{
flag = 1;
res1 = S.Substring(0, x + 1);
res2 = middle;
res3 = S.Substring(y);
break;
}
}
// Print the three palindromic
if (flag == 1)
{
Console.Write(res1 + " " +
res2 + " " + res3);
}
// Otherwise
else
Console.Write("-1");
}
// Driver Code
public static void Main(String[] args)
{
// Given String str
String str = "ababbcb";
int N = str.Length;
// Function Call
Palindromes(str, N);
}
}
// This code is contributed by Amit Katiyar
输出:
a bab bcb
时间复杂度: O(N 2 )
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live