📌  相关文章
📜  计算将字符串减少为单个不同字符所需的最小子字符串删除

📅  最后修改于: 2021-09-06 06:43:02             🧑  作者: Mango

给定一个字符串s由“X”,“Y”“Z”只,任务是与S转换为通过选择字符和删除子仅由单一的不同字符的字符串,不包含该字符的最小次数。

注意:一旦选择了一个字符,其他字符就不能用于进一步的操作。

例子:

方法:想法是使用 unordered_map 计算每个字符的出现次数,并计算每个字符所需的删除次数并打印最小值。请按照以下步骤解决问题:

  • 初始化 unordered_map 并存储每个字符的出现索引。
  • 迭代字符串S 的所有字符并更新映射中出现的字符“X”、“Y”“Z”
  • 遍历 Map 并为每个字符计算每个字符所需的移除次数。
  • 计算每个字符,打印为任何字符获得的最小计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find minimum removals
// required to convert given string
// to single distinct characters only
int minimumOperations(string s, int n)
{
 
    // Unordered map to store positions
    // of characters X, Y and Z
    unordered_map > mp;
 
    // Update indices of X, Y, Z;
    for (int i = 0; i < n; i++) {
        mp[s[i]].push_back(i);
    }
     
    // Stores the count of
    // minimum removals
    int ans = INT_MAX;
 
    // Traverse the Map
    for (auto x : mp) {
        int curr = 0;
        int prev = 0;
        bool first = true;
 
        // Count the number of removals
        // required for current character
        for (int index : (x.second)) {
            if (first) {
                if (index > 0) {
                    curr++;
                }
                prev = index;
                first = false;
            }
            else {
                if (index != prev + 1) {
                    curr++;
                }
                prev = index;
            }
        }
        if (prev != n - 1) {
            curr++;
        }
 
        // Update the answer
        ans = min(ans, curr);
    }
 
    // Print the answer
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given string
    string s = "YYXYZYXYZXY";
 
    // Size of string
    int N = s.length();
 
    // Function call
    minimumOperations(s, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
   
  // Function to find minimum removals
  // required to convert given string
  // to single distinct characters only
  static void minimumOperations(String s, int n)
  {
 
    // Unordered map to store positions
    // of characters X, Y and Z
    HashMap> mp = new HashMap<>();
 
    // Update indices of X, Y, Z;
    for(int i = 0; i < n; i++)
    {
      if (mp.containsKey(s.charAt(i)))
      {
        mp.get(s.charAt(i)).add(i);
      }
      else
      {
        mp.put(s.charAt(i), new ArrayList(Arrays.asList(i)));
      }
    }
 
    // Stores the count of
    // minimum removals
    int ans = Integer.MAX_VALUE;
 
    // Traverse the Map
    for (Map.Entry> x : mp.entrySet())
    {
      int curr = 0;
      int prev = 0;
      boolean first = true;
 
      // Count the number of removals
      // required for current character
      for(Integer index : (x.getValue()))
      {
        if (first)
        {
          if (index > 0)
          {
            curr++;
          }
          prev = index;
          first = false;
        }
        else
        {
          if (index != prev + 1)
          {
            curr++;
          }
          prev = index;
        }
      }
      if (prev != n - 1)
      {
        curr++;
      }
 
      // Update the answer
      ans = Math.min(ans, curr);
    }
 
    // Print the answer
    System.out.print(ans);
  }
     
  // Driver code
  public static void main(String[] args)
  {
 
    // Given string
    String s = "YYXYZYXYZXY";
 
    // Size of string
    int N = s.length();
 
    // Function call
    minimumOperations(s, N);
  }
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program for the above approach
import sys;
INT_MAX = sys.maxsize;
 
# Function to find minimum removals
# required to convert given string
# to single distinct characters only
def minimumOperations(s, n) :
 
    # Unordered map to store positions
    # of characters X, Y and Z
    mp = {};
 
    # Update indices of X, Y, Z;
    for i in range(n) :
        if s[i] in mp :
            mp[s[i]].append(i);
        else :
            mp[s[i]] = [i];
             
    # Stores the count of
    # minimum removals
    ans = INT_MAX;
 
    # Traverse the Map
    for x in mp :
        curr = 0;
        prev = 0;
        first = True;
 
        # Count the number of removals
        # required for current character
        for index in mp[x] :
            if (first) :
                if (index > 0) :
                    curr += 1;
                prev = index;
                first = False;
             
            else :
                if (index != prev + 1) :
                    curr += 1;
                prev = index;
                 
        if (prev != n - 1) :
            curr += 1;
 
        # Update the answer
        ans = min(ans, curr);
 
    # Print the answer
    print(ans);
 
# Driver Code
if __name__ == "__main__" :
 
    # Given string
    s = "YYXYZYXYZXY";
 
    # Size of string
    N = len(s);
 
    # Function call
    minimumOperations(s, N);
 
    # This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
using System.Collections.Generic; 
 
class GFG{
     
// Function to find minimum removals
// required to convert given string
// to single distinct characters only
static void minimumOperations(string s, int n)
{
     
    // Unordered map to store positions
    // of characters X, Y and Z
    Dictionary> mp = new Dictionary>(); 
  
    // Update indices of X, Y, Z;
    for(int i = 0; i < n; i++)
    {
        if (mp.ContainsKey(s[i]))
        {
            mp[s[i]].Add(i);
        }
        else
        {
            mp[s[i]] = new List();
            mp[s[i]].Add(i);
        }
    }
      
    // Stores the count of
    // minimum removals
    int ans = Int32.MaxValue;
  
    // Traverse the Map
    foreach(KeyValuePair> x in mp)
    {
        int curr = 0;
        int prev = 0;
        bool first = true;
  
        // Count the number of removals
        // required for current character
        foreach(int index in (x.Value))
        {
            if (first)
            {
                if (index > 0)
                {
                    curr++;
                }
                prev = index;
                first = false;
            }
            else
            {
                if (index != prev + 1)
                {
                    curr++;
                }
                prev = index;
            }
        }
        if (prev != n - 1)
        {
            curr++;
        }
  
        // Update the answer
        ans = Math.Min(ans, curr);
    }
  
    // Print the answer
    Console.Write(ans);
}
 
// Driver Code
static void Main()
{
     
    // Given string
    string s = "YYXYZYXYZXY";
     
    // Size of string
    int N = s.Length;
     
    // Function call
    minimumOperations(s, N);
}
}
 
// This code is contributed by divyesh072019


输出:
3

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live