📌  相关文章
📜  通过删除最多 2 个唯一字符出现来生成数字字符串回文的最小操作

📅  最后修改于: 2022-05-13 01:57:07.633000             🧑  作者: Mango

通过删除最多 2 个唯一字符出现来生成数字字符串回文的最小操作

给定数字字符串str ,任务是找到生成字符串回文所需的最少操作。操作定义为:

  • 选择一个字符并删除它的任何出现
  • 对于所有操作,选择的唯一字符数必须小于2

例子

方法:这个问题可以在两点方法的帮助下解决。
请按照以下步骤解决问题:

  1. 将变量answer初始化为 n 以存储我们的最终答案(n 是字符串的长度)。
  2. 遍历 '0' 到 '9',我们称它为 currentCharacter。
  3. toBeRemoved初始化为0 。它存储要从字符串中删除的currentCharacter类型的最小字符数,以使其成为回文。
  4. ij分别初始化为0n – 1
  5. 将 a possible初始化为true 。它可以帮助我们确定是否可以通过仅删除字符c 的出现来生成字符串回文。
  6. 现在运行一个嵌套的while循环,直到i小于j
    • 情况1:str[i]等于str[j],这意味着我们不需要在当前步骤删除任何字符,因此我们可以增加i和减少j。
    • 情况 2:str[i] 不等于 str[j] 但 str[i] 等于 currentCharacter。当我们删除这个字符时,增加i = i + 1toBeRemoved = toBeRemoved + 1
    • 情况 3:str[i] 不等于 str[j] 但 str[j] 等于 currentCharacter。增加j = j – 1toBeRemoved = toBeRemoved + 1因为我们要删除这个字符
    • 情况 4:str[i] 不等于 str[j]。这意味着我们不能通过删除currentCharacter来生成我们的字符串回文。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum operations
void solve(string str)
{
    // Length of the string
    int n = str.length();
 
    // answer variable for final answer
    // initializing it with INF
    int answer = n;
 
    // Iterating over characters
    // from '0' to '9' (string
    // consist of those characters only)
    for (char currentCharacter = '0';
         currentCharacter <= '9';
         currentCharacter++) {
 
        // i and j variables to check corresponding
        // characters from the start and the end
        int i = 0, j = n - 1;
 
        // toBeRemoved store the character of type
        // currentCharacter to be removed
        // to make the string palindrome
 
        int toBeRemoved = 0;
        bool possible = true;
        while (i < j) {
            // If corresponding currentCharacters are
            // already same
            if (str[i] == str[j]) {
                i++, j--;
            }
 
            // If corresponding currentCharacters are
            // not same and str[i] is equal to
            // currentCharacter
            // remove it and check for str[i + 1] and
            // str[j] in the next iteration
            else if (str[i] != str[j]
                     && str[i] == currentCharacter) {
                toBeRemoved++;
                i++;
            }
 
            // If corresponding currentCharacters are
            // not same and str[j] is equal to
            // currentCharacter
            // remove it and check for str[j - 1] and
            // str[i] in the next iteration
            else if (str[i] != str[j]
                     && str[j] == currentCharacter) {
                toBeRemoved++;
                j--;
            }
 
            // Character of currentCharacter type
            // can't be removed
            // to make the str palindrome.
            // Hence, we mark possible to false
            // break out of the loop
            else {
                possible = false;
                break;
            }
        }
 
        // If it is possible to remove
        // some occurrences of currentCharacters
        // we will update our answer
        if (possible)
 
            // Take the minimum value out
            // of answer and toBeRemoved
            answer = min(answer, toBeRemoved);
    }
 
    // Print the final answer
    if (answer == n)
        cout << "-1";
    else
        cout << answer;
}
 
// Driver Code
int main()
{
    // Given string
    string str = "11221";
    solve(str);
}


Java
// Java code for the above approach
import java.io.*;
 
class GFG
{
   
  // Function to find the minimum operations
  static void solve(String str)
  {
    // Length of the string
    int n = str.length();
 
    // answer variable for final answer
    // initializing it with INF
    int answer = n;
 
    // Iterating over characters
    // from '0' to '9' (string
    // consist of those characters only)
    for (char currentCharacter = '0';
         currentCharacter <= '9';
         currentCharacter++) {
 
      // i and j variables to check corresponding
      // characters from the start and the end
      int i = 0, j = n - 1;
 
      // toBeRemoved store the character of type
      // currentCharacter to be removed
      // to make the string palindrome
 
      int toBeRemoved = 0;
      boolean possible = true;
      while (i < j) {
        // If corresponding currentCharacters are
        // already same
        if (str.charAt(i) == str.charAt(j)) {
          i++; j--;
        }
 
        // If corresponding currentCharacters are
        // not same and str[i] is equal to
        // currentCharacter
        // remove it and check for str[i + 1] and
        // str[j] in the next iteration
        else if (str.charAt(i) != str.charAt(j)
                 && str.charAt(i) == currentCharacter) {
          toBeRemoved++;
          i++;
        }
 
        // If corresponding currentCharacters are
        // not same and str[j] is equal to
        // currentCharacter
        // remove it and check for str[j - 1] and
        // str[i] in the next iteration
        else if (str.charAt(i) != str.charAt(j)
                 && str.charAt(j)  == currentCharacter) {
          toBeRemoved++;
          j--;
        }
 
        // Character of currentCharacter type
        // can't be removed
        // to make the str palindrome.
        // Hence, we mark possible to false
        // break out of the loop
        else {
          possible = false;
          break;
        }
      }
 
      // If it is possible to remove
      // some occurrences of currentCharacters
      // we will update our answer
      if (possible)
 
        // Take the minimum value out
        // of answer and toBeRemoved
        answer = Math.min(answer, toBeRemoved);
    }
 
    // Print the final answer
    if (answer == n)
      System.out.println("-1");
    else
      System.out.println(answer);
  }
 
  // Driver Code
  public static void main (String[] args)
  {
 
    // Given string
    String str = "11221";
    solve(str);
  }
}
 
// This code is contributed by lokeshpotta20.


Python3
# Python program for the above approach
 
# Function to find the minimum operations
def solve(str):
   
    # Length of the string
    n = len(str)
 
    # answer variable for final answer
    # initializing it with INF
    answer = n;
    currentCharacter = '0'
     
    # Iterating over characters
    # from '0' to '9' (string
    # consist of those characters only)
    while(currentCharacter <= '9'):
 
        # i and j variables to check corresponding
        # characters from the start and the end
        i = 0
        j = n - 1
 
        # toBeRemoved store the character of type
        # currentCharacter to be removed
        # to make the string palindrome
        toBeRemoved = 0
        possible = True
        while (i < j):
           
            # If corresponding currentCharacters are
            # already same
            if (str[i] == str[j]):
                i += 1
                j -= 1
             
            # If corresponding currentCharacters are
            # not same and str[i] is equal to
            # currentCharacter
            # remove it and check for str[i + 1] and
            # str[j] in the next iteration
            elif (str[i] != str[j] and str[i] == currentCharacter):
                toBeRemoved += 1   
                i += 1
             
            # If corresponding currentCharacters are
            # not same and str[j] is equal to
            # currentCharacter
            # remove it and check for str[j - 1] and
            # str[i] in the next iteration
            elif (str[i] != str[j] and str[j] == currentCharacter):
                toBeRemoved += 1
                j -= 1
             
            # Character of currentCharacter type
            # can't be removed
            # to make the str palindrome.
            # Hence, we mark possible to false
            # break out of the loop
            else:
                possible = False;
                break;
 
            currentCharacter = f"{int(currentCharacter) + 1}"
             
        # If it is possible to remove
        # some occurrences of currentCharacters
        # we will update our answer
        if (possible):
 
            # Take the minimum value out
            # of answer and toBeRemoved
            answer = min(answer, toBeRemoved);
     
    # Print the final answer
    if (answer == n):
        print("-1");
    else:
        print(answer);
 
# Driver Code
 
# Given string
str = "11221";
solve(str);
 
# This code is contributed by Saurabh Jaiswal


C#
// C# program for above approach
using System;
class GFG
{
 
// Function to find the minimum operations
static void solve(string str)
{
    // Length of the string
    int n = str.Length;
 
    // answer variable for final answer
    // initializing it with INF
    int answer = n;
 
    // Iterating over characters
    // from '0' to '9' (string
    // consist of those characters only)
    for (char currentCharacter = '0';
         currentCharacter <= '9';
         currentCharacter++) {
 
        // i and j variables to check corresponding
        // characters from the start and the end
        int i = 0, j = n - 1;
 
        // toBeRemoved store the character of type
        // currentCharacter to be removed
        // to make the string palindrome
 
        int toBeRemoved = 0;
        bool possible = true;
        while (i < j) {
            // If corresponding currentCharacters are
            // already same
            if (str[i] == str[j]) {
                i++;
                j--;
            }
 
            // If corresponding currentCharacters are
            // not same and str[i] is equal to
            // currentCharacter
            // remove it and check for str[i + 1] and
            // str[j] in the next iteration
            else if (str[i] != str[j]
                     && str[i] == currentCharacter) {
                toBeRemoved++;
                i++;
            }
 
            // If corresponding currentCharacters are
            // not same and str[j] is equal to
            // currentCharacter
            // remove it and check for str[j - 1] and
            // str[i] in the next iteration
            else if (str[i] != str[j]
                     && str[j] == currentCharacter) {
                toBeRemoved++;
                j--;
            }
 
            // Character of currentCharacter type
            // can't be removed
            // to make the str palindrome.
            // Hence, we mark possible to false
            // break out of the loop
            else {
                possible = false;
                break;
            }
        }
 
        // If it is possible to remove
        // some occurrences of currentCharacters
        // we will update our answer
        if (possible)
 
            // Take the minimum value out
            // of answer and toBeRemoved
            answer = Math.Min(answer, toBeRemoved);
    }
 
    // Print the final answer
    if (answer == n)
        Console.Write("-1");
    else
        Console.Write(answer);
}
 
// Driver Code
public static void Main()
{
    // Given string
    string str = "11221";
    solve(str);
}
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
1

时间复杂度 O(10 * n) = O(n) 其中 n 是字符串str 的长度。
辅助空间 O(1)