📌  相关文章
📜  检查回文字符串可以通过串联从两个给定字符串的相同索引中分割的子字符串来获得

📅  最后修改于: 2021-05-14 02:19:42             🧑  作者: Mango

给定两个长度为N的字符串AB ,任务是检查两个字符串的任何一个是否通过将两个字符串在任意索引i (0≤i≤N – 1)上分割并连接A [0,i]B形成[i,N – 1]A [i,N – 1]B [0,i]是否形成回文字符串。如果发现是真的,则打印“是” 。否则,打印“否”

例子:

方法:想法是使用双指针技术并遍历[0,N – 1]范围内的字符串并检查子字符串A [0,i – 1]B [i,N – 1]的串联还是子串A [i,N – 1]B [0,i – 1]的串联是否为回文。如果发现任何串联是回文的,则打印“是”,否则打印“否”

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to check if a string
// is palindrome or not
bool isPalindrome(string str)
{
  // Start and end of the
  // string
  int i = 0, j = str.size() - 1;
 
  // Iterate the string
  // until i > j
  while (i < j)
  {
    // If there is a mismatch
    if (str[i] != str[j])
      return false;
 
    // Increment first pointer
    // and decrement the other
    i++;
    j--;
  }
 
  // Given string is a
  // palindrome
  return true;
}
 
// Function two check if
// the strings can be
// combined to form a palindrome
void formPalindrome(string a,
                    string b, int n)
{
  // Initialize array of
  // characters
  char aa[n + 2];
  char bb[n + 2];
  for (int i = 0; i < n + 2; i++)
  {
    aa[i] = ' ';
    bb[i] = ' ';
  }
  // Stores character of string
  // in the character array
  for (int i = 1; i <= n; i++)
  {
    aa[i] = a[i - 1];
    bb[i] = b[i - 1];
  }
 
  bool ok = false;
 
  for (int i = 0; i <= n + 1; i++)
  {
    // Find left and right parts
    // of strings a and b
    string la = "";
    string ra = "";
    string lb = "";
    string rb = "";
 
    for (int j = 1; j <= i - 1; j++)
    {
      // Substring a[j...i-1]
      if (aa[j] == ' ')
        la += "";
      else
        la += aa[j];
 
      // Substring b[j...i-1]
      if (bb[j] == ' ')
        lb += "";
      else
        lb += bb[j];
    }
 
    for (int j = i; j <= n + 1; j++)
    {
      // Substring a[i...n]
      if (aa[j] == ' ')
        ra += "";
      else
        ra += aa[j];
 
      // Substring b[i...n]
      if (bb[j] == ' ')
        rb += "";
      else
        rb += bb[j];
    }
 
    // Check is left part of a +
    // right part of b or vice
    // versa is a palindrome
    if (isPalindrome(la + rb) ||
        isPalindrome(lb + ra))
    {
      ok = true;
      break;
    }
  }
 
  // Print the result
  if (ok)
    cout << ("Yes");
 
  // Otherwise
  else
    cout << ("No");
}
 
// Driver Code
int main()
{
  string A = "bdea";
  string B = "abbb";
  int N = 4;
  formPalindrome(A, B, N);
}
 
// This code is contributed by gauravrajput1


Java
// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to check if a string
    // is palindrome or not
    static boolean isPalindrome(String str)
    {
 
        // Start and end of the string
        int i = 0, j = str.length() - 1;
 
        // Iterate the string until i > j
        while (i < j) {
 
            // If there is a mismatch
            if (str.charAt(i)
                != str.charAt(j))
                return false;
 
            // Increment first pointer and
            // decrement the other
            i++;
            j--;
        }
 
        // Given string is a palindrome
        return true;
    }
 
    // Function two check if the strings can
    // be combined to form a palindrome
    static void formPalindrome(
        String a, String b, int n)
    {
        // Initialize array of characters
        char aa[] = new char[n + 2];
        char bb[] = new char[n + 2];
 
        Arrays.fill(aa, ' ');
        Arrays.fill(bb, ' ');
 
        // Stores character of string
        // in the character array
        for (int i = 1; i <= n; i++) {
            aa[i] = a.charAt(i - 1);
            bb[i] = b.charAt(i - 1);
        }
 
        boolean ok = false;
 
        for (int i = 0; i <= n + 1; i++) {
 
            // Find left and right parts
            // of strings a and b
            StringBuilder la
                = new StringBuilder();
            StringBuilder ra
                = new StringBuilder();
            StringBuilder lb
                = new StringBuilder();
            StringBuilder rb
                = new StringBuilder();
 
            for (int j = 1;
                 j <= i - 1; j++) {
 
                // Substring a[j...i-1]
                la.append((aa[j] == ' ')
                              ? ""
                              : aa[j]);
 
                // Substring b[j...i-1]
                lb.append((bb[j] == ' ')
                              ? ""
                              : bb[j]);
            }
 
            for (int j = i;
                 j <= n + 1; j++) {
 
                // Substring a[i...n]
                ra.append((aa[j] == ' ')
                              ? ""
                              : aa[j]);
 
                // Substring b[i...n]
                rb.append((bb[j] == ' ')
                              ? ""
                              : bb[j]);
            }
 
            // Check is left part of a +
            // right part of b or vice
            // versa is a palindrome
            if (isPalindrome(la.toString()
                             + rb.toString())
                || isPalindrome(lb.toString()
                                + ra.toString())) {
                ok = true;
                break;
            }
        }
 
        // Print the result
        if (ok)
            System.out.println("Yes");
 
        // Otherwise
        else
            System.out.println("No");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String A = "bdea";
        String B = "abbb";
 
        int N = 4;
 
        formPalindrome(A, B, N);
    }
}


Python3
# Python3 program for the
# above approach
 
# Function to check if
# a string is palindrome
# or not
def isPalindrome(st):
 
    # Start and end of
    # the string
    i = 0
    j = len(st) - 1
 
    # Iterate the string
    # until i > j
    while (i < j):
 
        # If there is a mismatch
        if (st[i] != st[j]):
            return False
 
        # Increment first pointer
        # and decrement the other
        i += 1
        j -= 1
 
    # Given string is a
    # palindrome
    return True
 
# Function two check if
# the strings can be
# combined to form a
# palindrome
def formPalindrome(a, b, n):
 
    # Initialize array of
    # characters
    aa = [' '] * (n + 2)
    bb = [' '] * (n + 2)
 
    # Stores character of string
    # in the character array
    for i in range(1, n + 1):
        aa[i] = a[i - 1]
        bb[i] = b[i - 1]
 
    ok = False
 
    for i in range(n + 2):
 
        # Find left and right parts
        # of strings a and b
        la = ""
        ra = ""
        lb = ""
        rb = ""
 
        for j in range(1, i):
 
            # Substring a[j...i-1]
            if (aa[j] == ' '):
                la += ""
            else:
                la += aa[j]
 
            # Substring b[j...i-1]
            if (bb[j] == ' '):
                lb += ""
            else:
                lb += bb[j]
 
        for j in range(i, n + 2):
 
            # Substring a[i...n]
            if (aa[j] == ' '):
                ra += ""
            else:
                ra += aa[j]
 
            # Substring b[i...n]
            if (bb[j] == ' '):
                rb += ""
            else:
                rb += bb[j]
 
        # Check is left part of a +
        # right part of b or vice
        # versa is a palindrome
        if (isPalindrome(str(la) +
                         str(rb))
            or isPalindrome(str(lb) +
                            str(ra))):
            ok = True
            break
 
    # Print the result
    if (ok):
        print("Yes")
 
    # Otherwise
    else:
        print("No")
 
# Driver Code
if __name__ == "__main__":
 
    A = "bdea"
    B = "abbb"
    N = 4
    formPalindrome(A, B, N)
 
# This code is contributed by Chitranayal


C#
// C# program for the
// above approach
using System;
using System.Text;
class GFG{
 
// Function to check if a string
// is palindrome or not
static bool isPalindrome(String str)
{
  // Start and end of the string
  int i = 0, j = str.Length - 1;
 
  // Iterate the string
  // until i > j
  while (i < j)
  {
    // If there is a mismatch
    if (str[i] != str[j])
      return false;
 
    // Increment first pointer
    // and decrement the other
    i++;
    j--;
  }
 
  // Given string is
  // a palindrome
  return true;
}
 
// Function two check if the strings can
// be combined to form a palindrome
static void formPalindrome(String a,
                           String b, int n)
{
  // Initialize array of
  // characters
  char []aa = new char[n + 2];
  char []bb = new char[n + 2];
 
  for(int i = 0; i < n + 2; i++)
  {
    aa[i] = ' ';
    bb[i] = ' ';
  }
 
  // Stores character of string
  // in the character array
  for (int i = 1; i <= n; i++)
  {
    aa[i] = a[i-1];
    bb[i] = b[i-1];
  }
 
  bool ok = false;
 
  for (int i = 0;
           i <= n + 1; i++)
  {
    // Find left and right parts
    // of strings a and b
    StringBuilder la =
          new StringBuilder();
    StringBuilder ra =
          new StringBuilder();
    StringBuilder lb =
          new StringBuilder();
    StringBuilder rb =
          new StringBuilder();
 
    for (int j = 1;
             j <= i - 1; j++)
    {
      // Substring a[j...i-1]
      la.Append((aa[j] == ' ') ?
                ' ' : aa[j]);
 
      // Substring b[j...i-1]
      lb.Append((bb[j] == ' ') ?
                ' ' : bb[j]);
    }
 
    for (int j = i;
             j <= n + 1; j++)
    {
      // Substring a[i...n]
      ra.Append((aa[j] == ' ') ?
                ' ' : aa[j]);
 
      // Substring b[i...n]
      rb.Append((bb[j] == ' ') ?
                ' ' : bb[j]);
    }
 
    // Check is left part of a +
    // right part of b or vice
    // versa is a palindrome
    if (isPalindrome(la.ToString() +
                     rb.ToString()) ||
        isPalindrome(lb.ToString() +
                     ra.ToString()))
    {
      ok = true;
      break;
    }
  }
 
  // Print the result
  if (!ok)
    Console.WriteLine("Yes");
 
  // Otherwise
  else
    Console.WriteLine("No");
}
 
// Driver Code
public static void Main(String[] args)
{
  String A = "bdea";
  String B = "abbb";
  int N = 4;
  formPalindrome(A, B, N);
}
}
 
// This code is contributed by 29AjayKumar


C++
// C++ program to implement
// the above approach
#include
using namespace std;
 
string rev(string str)
{
  int st = 0;
  int ed = str.length() - 1;
  string s = str;
   
  while(st < ed)
  {
    swap(s[st],
         s[ed]);
    st++;
    ed--;
  }
  return s;
}
 
 
bool check(string a,
           string b, int n)
{
  int i = 0;
  int j = n - 1;
 
  // iterate through the
  // length if we could
  // find a[i]==b[j] we could
  // increment I and decrement j
  while(i < n)
  {
    if(a[i] != b[j])
      break;
 
    // else we could just break
    // the loop as its not a
    // palindrome type sequence
    i += 1;
    j -= 1;
 
    // we could concatenate the
    // a's left part +b's right
    // part in a variable a and
    // a's right part+b's left
    // in the variable b
    string xa = a.substr(i, j + 1 - i);
    string xb = b.substr(i, j + 1 - i);
 
    // we would check for the
    // palindrome condition if
    // yes we print True else False
    if((xa == rev(xa)) or
       (xb == rev(xb)))
      return true;
  }
  return false;
}
     
// Driver code
int main()
{
  string a = "xbdef";
  string b = "cabex";
  if (check(a, b,
            a.length()) == true or
      check(b, a,
            a.length()) == true)
    cout << "True";
  else
    cout << "False";
}
 
// This code is contributed by Surendra_Gangwar


Java
// Java program to implement
// the above approach
import java.util.*;
import java.io.*;
 
class GFG{
     
public static String rev(String str)
{
    int st = 0;
    int ed = str.length() - 1;
    char[] s = str.toCharArray();
     
    while(st < ed)
    {
        char temp = s[st];
        s[st] = s[ed];
        s[ed] = temp;
        st++;
        ed--;
    }
    return (s.toString());
}
   
public static boolean check(String a,
                            String b, int n)
{
    int i = 0;
    int j = n - 1;
     
    // Iterate through the
    // length if we could
    // find a[i]==b[j] we could
    // increment I and decrement j
    while(i < n)
    {
        if (a.charAt(i) != b.charAt(j))
            break;
         
        // Else we could just break
        // the loop as its not a
        // palindrome type sequence
        i += 1;
        j -= 1;
         
        // We could concatenate the
        // a's left part +b's right
        // part in a variable a and
        // a's right part+b's left
        // in the variable b
        String xa = a.substring(i, j + 1);
        String xb = b.substring(i, j + 1);
         
        // We would check for the
        // palindrome condition if
        // yes we print True else False
        StringBuffer XA = new StringBuffer(xa);
        XA.reverse();
        StringBuffer XB = new StringBuffer(xb);
        XB.reverse();
         
        if (xa == XA.toString() ||
            xb == XB.toString())
        {
            return true;
        }
    }
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    String a = "xbdef";
    String b = "cabex";
     
    if (check(a, b, a.length()) ||
        check(b, a, a.length()))
        System.out.println("True");
    else
        System.out.println("False");
}
}
 
// This code is contributed by divyesh072019


Python3
# Python3 program to implement
# the above approach
def check(a, b, n):
    i, j = 0, n - 1
     
    # iterate through the length if
    # we could find a[i]==b[j] we could
    # increment I and decrement j
    while(i < n):
        if(a[i] != b[j]):
             
            # else we could just break
            # the loop as its not a palindrome
            # type sequence
            break 
             
        i += 1
        j -= 1
         
        # we could concatenate the a's left part
        # +b's right part in a variable a and  a's
        # right part+b's left in the variable b
        xa = a[i:j+1]
        xb = b[i:j+1]
         
        # we would check for the palindrome condition
        # if yes we print True else False
        if(xa == xa[::-1] or xb == xb[::-1]):
            return True
 
 
a = "xbdef"
b = "cabex"
if check(a, b, len(a)) == True or check(b, a, len(a)) == True:
    print(True)
else:
    print(False)
 
     
# CODE CONTRIBUTED BY SAIKUMAR KUDIKALA


C#
// C# program to implement
// the above approach
using System;
class GFG {
     
    static string rev(string str)
    {
      int st = 0;
      int ed = str.Length - 1;
      char[] s = str.ToCharArray();
     
      while(st < ed)
      {
        char temp = s[st];
        s[st] = s[ed];
        s[ed] = temp;
        st++;
        ed--;
      }
      return new string(s);
    }
      
      
    static bool check(string a,
               string b, int n)
    {
      int i = 0;
      int j = n - 1;
      
      // iterate through the
      // length if we could
      // find a[i]==b[j] we could
      // increment I and decrement j
      while(i < n)
      {
        if(a[i] != b[j])
          break;
      
        // else we could just break
        // the loop as its not a
        // palindrome type sequence
        i += 1;
        j -= 1;
      
        // we could concatenate the
        // a's left part +b's right
        // part in a variable a and
        // a's right part+b's left
        // in the variable b
        string xa = a.Substring(i, j + 1 - i);
        string xb = b.Substring(i, j + 1 - i);
      
        // we would check for the
        // palindrome condition if
        // yes we print True else False
        char[] XA = xa.ToCharArray();
        Array.Reverse(XA);
        char[] XB = xb.ToCharArray();
        Array.Reverse(XB);
         
        if(string.Compare(xa, new string(XA)) == 0 ||
           string.Compare(xb, new string(XB)) == 0)
          return true;
      }
      return false;
    }
 
  // Driver code
  static void Main()
  {
      string a = "xbdef";
      string b = "cabex";
      if (check(a, b, a.Length) || check(b, a, a.Length))
        Console.WriteLine("True");
      else
        Console.WriteLine("False");
  }
}
 
// This code is contributed by divyeshrabadiya07


输出
Yes

时间复杂度: O(N 2 ),其中N是给定字符串的长度。
辅助空间: O(N)

备用Python方法(两个指针+切片):

此方法遵循以下路径:

  1. 定义函数检查
  2. 分别在0,n-1位置取两个指针i,j
  3. 如果B的和第二字符的第一个字符不符合我们打破(因为我们正在寻找回文)
  4. 如果匹配,我们只需增加指针
  5. 我们将串连形式的[I:J + 1]第一字符串和b的[I:J + 1]所述第二字符串并检查回文的条件
  6. 如果是,我们返回True

C++

// C++ program to implement
// the above approach
#include
using namespace std;
 
string rev(string str)
{
  int st = 0;
  int ed = str.length() - 1;
  string s = str;
   
  while(st < ed)
  {
    swap(s[st],
         s[ed]);
    st++;
    ed--;
  }
  return s;
}
 
 
bool check(string a,
           string b, int n)
{
  int i = 0;
  int j = n - 1;
 
  // iterate through the
  // length if we could
  // find a[i]==b[j] we could
  // increment I and decrement j
  while(i < n)
  {
    if(a[i] != b[j])
      break;
 
    // else we could just break
    // the loop as its not a
    // palindrome type sequence
    i += 1;
    j -= 1;
 
    // we could concatenate the
    // a's left part +b's right
    // part in a variable a and
    // a's right part+b's left
    // in the variable b
    string xa = a.substr(i, j + 1 - i);
    string xb = b.substr(i, j + 1 - i);
 
    // we would check for the
    // palindrome condition if
    // yes we print True else False
    if((xa == rev(xa)) or
       (xb == rev(xb)))
      return true;
  }
  return false;
}
     
// Driver code
int main()
{
  string a = "xbdef";
  string b = "cabex";
  if (check(a, b,
            a.length()) == true or
      check(b, a,
            a.length()) == true)
    cout << "True";
  else
    cout << "False";
}
 
// This code is contributed by Surendra_Gangwar

Java

// Java program to implement
// the above approach
import java.util.*;
import java.io.*;
 
class GFG{
     
public static String rev(String str)
{
    int st = 0;
    int ed = str.length() - 1;
    char[] s = str.toCharArray();
     
    while(st < ed)
    {
        char temp = s[st];
        s[st] = s[ed];
        s[ed] = temp;
        st++;
        ed--;
    }
    return (s.toString());
}
   
public static boolean check(String a,
                            String b, int n)
{
    int i = 0;
    int j = n - 1;
     
    // Iterate through the
    // length if we could
    // find a[i]==b[j] we could
    // increment I and decrement j
    while(i < n)
    {
        if (a.charAt(i) != b.charAt(j))
            break;
         
        // Else we could just break
        // the loop as its not a
        // palindrome type sequence
        i += 1;
        j -= 1;
         
        // We could concatenate the
        // a's left part +b's right
        // part in a variable a and
        // a's right part+b's left
        // in the variable b
        String xa = a.substring(i, j + 1);
        String xb = b.substring(i, j + 1);
         
        // We would check for the
        // palindrome condition if
        // yes we print True else False
        StringBuffer XA = new StringBuffer(xa);
        XA.reverse();
        StringBuffer XB = new StringBuffer(xb);
        XB.reverse();
         
        if (xa == XA.toString() ||
            xb == XB.toString())
        {
            return true;
        }
    }
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    String a = "xbdef";
    String b = "cabex";
     
    if (check(a, b, a.length()) ||
        check(b, a, a.length()))
        System.out.println("True");
    else
        System.out.println("False");
}
}
 
// This code is contributed by divyesh072019

Python3

# Python3 program to implement
# the above approach
def check(a, b, n):
    i, j = 0, n - 1
     
    # iterate through the length if
    # we could find a[i]==b[j] we could
    # increment I and decrement j
    while(i < n):
        if(a[i] != b[j]):
             
            # else we could just break
            # the loop as its not a palindrome
            # type sequence
            break 
             
        i += 1
        j -= 1
         
        # we could concatenate the a's left part
        # +b's right part in a variable a and  a's
        # right part+b's left in the variable b
        xa = a[i:j+1]
        xb = b[i:j+1]
         
        # we would check for the palindrome condition
        # if yes we print True else False
        if(xa == xa[::-1] or xb == xb[::-1]):
            return True
 
 
a = "xbdef"
b = "cabex"
if check(a, b, len(a)) == True or check(b, a, len(a)) == True:
    print(True)
else:
    print(False)
 
     
# CODE CONTRIBUTED BY SAIKUMAR KUDIKALA

C#

// C# program to implement
// the above approach
using System;
class GFG {
     
    static string rev(string str)
    {
      int st = 0;
      int ed = str.Length - 1;
      char[] s = str.ToCharArray();
     
      while(st < ed)
      {
        char temp = s[st];
        s[st] = s[ed];
        s[ed] = temp;
        st++;
        ed--;
      }
      return new string(s);
    }
      
      
    static bool check(string a,
               string b, int n)
    {
      int i = 0;
      int j = n - 1;
      
      // iterate through the
      // length if we could
      // find a[i]==b[j] we could
      // increment I and decrement j
      while(i < n)
      {
        if(a[i] != b[j])
          break;
      
        // else we could just break
        // the loop as its not a
        // palindrome type sequence
        i += 1;
        j -= 1;
      
        // we could concatenate the
        // a's left part +b's right
        // part in a variable a and
        // a's right part+b's left
        // in the variable b
        string xa = a.Substring(i, j + 1 - i);
        string xb = b.Substring(i, j + 1 - i);
      
        // we would check for the
        // palindrome condition if
        // yes we print True else False
        char[] XA = xa.ToCharArray();
        Array.Reverse(XA);
        char[] XB = xb.ToCharArray();
        Array.Reverse(XB);
         
        if(string.Compare(xa, new string(XA)) == 0 ||
           string.Compare(xb, new string(XB)) == 0)
          return true;
      }
      return false;
    }
 
  // Driver code
  static void Main()
  {
      string a = "xbdef";
      string b = "cabex";
      if (check(a, b, a.Length) || check(b, a, a.Length))
        Console.WriteLine("True");
      else
        Console.WriteLine("False");
  }
}
 
// This code is contributed by divyeshrabadiya07

输出:

False