📌  相关文章
📜  删除给定数量的字符后,检查字符串仍然回文

📅  最后修改于: 2021-05-08 17:10:26             🧑  作者: Mango

给定回文字符串str和整数N。任务是查找是否有可能从给定的字符串中准确删除N个字符,以使该字符串保持回文。

例子:

方法:可以观察到,总是可以从回文字符串删除小于或等于其长度的任意数量的字符,以使所得字符串仍为回文字符串。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function that returns true if str
// remains a palindrome after removing
// exactly N characters from it
bool isPossible(string str, int n)
{
    // Find the length of the string
    int len = str.length();
  
    // If it is possible
    if (len >= n)
        return true;
  
    return false;
}
  
// Driver code
int main()
{
    string str = "abccba";
    int n = 4;
  
    if (isPossible(str, n))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}


Java
// Java implementation of the approach
class GFG 
{
      
    // Function that returns true if str
    // remains a palindrome after removing
    // exactly N characters from it
    static boolean isPossible(String str, int n)
    {
        // Find the length of the string
        int len = str.length();
      
        // If it is possible
        if (len >= n)
            return true;
      
        return false;
    }
      
    // Driver code
    public static void main (String[] args)
    {
        String str = "abccba";
        int n = 4;
      
        if (isPossible(str, n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by AnkitRai01


Python
# Python3 implementation of the approach
  
# Function that returns true if str 
# remains a palindrome after removing 
# exactly N characters from it
def isPossible(str, n):
      
    # Find the length of the string
    l = len(str)
  
    # If it is possible
    if (l >= n):
        return True
      
    return False
  
# Driver code
str = "abccba"
n = 4
  
if(isPossible(str, n)):
    print("Yes")
else:
    print("No")


C#
// C# implementation of the approach
using System;
  
class GFG 
{
      
    // Function that returns true if str
    // remains a palindrome after removing
    // exactly N characters from it
    static bool isPossible(String str, int n)
    {
        // Find the length of the string
        int len = str.Length;
      
        // If it is possible
        if (len >= n)
            return true;
      
        return false;
    }
      
    // Driver code
    public static void Main(String[] args)
    {
        String str = "abccba";
        int n = 4;
      
        if (isPossible(str, n))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This code is contributed by PrinciRaj1992


输出:
Yes

时间复杂度: O(1)