给定的是一个整数数组Arr 。任务是确定数组是否有任何至少长度为 3 的回文子序列。
例子:
Input: Arr[] = [1, 2, 1]
Output: YES
Explanation:
Here 1 2 1 is a palindrome.
Input: Arr[] = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
Output: NO
Explanation:
Here no subsequence of length at least 3
exists which is a palindrome.
方法:
- 这个想法是只检查长度为 3 的,因为如果存在长度大于 3 的回文子序列,那么总是存在长度为 3 的回文子序列。
- 要找到长度为 3 的回文子序列,我们只需要找到一对相等的不相邻数。
下面是上述方法的实现:
C++
// C++ code to check if
// palindromic subsequece of
// length atleast 3 exist or not
#include
using namespace std;
string SubPalindrome(int n, int arr[])
{
bool ok = false;
for (int i = 0; i < n; i++)
{
for(int j = i + 2; j < n; j++)
{
if(arr[i] == arr[j])
ok = true;
}
}
if(ok)
return "YES";
else
return "NO";
}
// Driver code
int main()
{
// Input values to list
int Arr[] = {1, 2, 2, 3, 2};
// Calculating length of array
int N = sizeof(Arr)/sizeof(Arr[0]);
cout << SubPalindrome(N, Arr);
}
// This code is contributed by Bhupendra_Singh
Java
// Java code to check if
// palindromic subsequece of
// length atleast 3 exist or not
import java.util.*;
class GFG{
static String SubPalindrome(int n, int arr[])
{
boolean ok = false;
for (int i = 0; i < n; i++)
{
for(int j = i + 2; j < n; j++)
{
if(arr[i] == arr[j])
ok = true;
}
}
if(ok)
return "YES";
else
return "NO";
}
// Driver code
public static void main(String[] args)
{
// Input values to list
int Arr[] = {1, 2, 2, 3, 2};
// Calculating length of array
int N = Arr.length;
System.out.print(SubPalindrome(N, Arr));
}
}
// This code contributed by sapnasingh4991
Python3
# Python 3 code to check if
# palindromic subsequece of
# length atleast 3 exist or not
def SubPalindrome (n, arr):
ok = False
for i in range(n):
for j in range(i + 2, n):
if arr[i] == arr[j]:
ok = True
return('YES' if ok else 'NO')
# Driver code
# Input values to list
Arr = [1, 2, 2, 3, 2]
# Calculating length of the array
N = len(arr)
print (SubPalindrome(N, Arr))
C#
// C# code to check if
// palindromic subsequece of
// length atleast 3 exist or not
using System;
public class GFG{
static string SubPalindrome(int n, int []arr)
{
bool ok = false;
for(int i = 0; i < n; i++)
{
for(int j = i + 2; j < n; j++)
{
if(arr[i] == arr[j])
ok = true;
}
}
if(ok)
return "YES";
else
return "NO";
}
// Driver code
static public void Main ()
{
// Input values to list
int []Arr = { 1, 2, 2, 3, 2 };
// Calculating length of array
int N = Arr.Length;
Console.WriteLine(SubPalindrome(N, Arr));
}
}
// This code is contributed by shivanisinghss2110
Javascript
输出:
YES
时间复杂度: O(N^2)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live