📌  相关文章
📜  减少字符串中唯一字符的数量

📅  最后修改于: 2021-05-24 20:57:42             🧑  作者: Mango

给定两个字符串A和B由两种交换A [I]与B [I]或保持它不变最小化独特字符字符串A的数量。交换的数量可以大于或等于0。请注意,A [i]只能与B中相同的索引元素交换。打印最小数量的唯一字符。约束:0

例子:

Input : A = ababa
        B = babab
Output : 1
Swapping all b's in string A, with
a's in string B results in string
A having all characters as a. 

Input : A = abaaa
        B = bbabb
Output : 2
Initially string A has 2 unique
characters. Swapping at any index 
does not change this count.

推荐:请首先在IDE上尝试您的方法,然后查看解决方案。

方法:可以使用回溯解决问题。创建一个键为A [i]且值为对应字符的计数的映射。映射的大小表明了不同字符的数量,因为只有字符串A中存在的那些元素才作为映射中的键出现。在每个索引位置,都有两种选择:将A [i]与B [i]交换或保持A [i]不变。从索引0开始,并对每个索引执行以下操作:

  1. 保持A [i]不变,在映射中将A [i]的计数加1,然后递归调用下一个索引。
  2. 通过将A [i]的计数减1,将A [i]与B [i]交换,在映射中将A [i]的计数增1进行回溯,并再次递归调用下一个索引。

保留变量ans以存储不同字符的整体最小值。在上述两种情况下,遍历整个字符串时,将当前的不同字符与ans的最小值进行比较,并相应地更新ans。

执行:

// CPP program to minimize number of
// unique characters in a string.
  
#include 
using namespace std;
  
// Utility function to find minimum
// number of unique characters in string.
void minCountUtil(string A, string B,
                  unordered_map& ele,
                  int& ans, int ind)
{
  
    // If entire string is traversed, then
    // compare current number of distinct
    // characters in A with overall minimum.
    if (ind == A.length()) {
        ans = min(ans, (int)ele.size());
        return;
    }
  
    // swap A[i] with B[i], increase count of
    // corresponding character in map and call
    // recursively for next index.
    swap(A[ind], B[ind]);
    ele[A[ind]]++;
    minCountUtil(A, B, ele, ans, ind + 1);
  
    // Backtrack (Undo the changes done)
    ele[A[ind]]--;
  
    // If count of character is reduced to zero,
    // then that character is not present in A.
    // So remove that character from map.
    if (ele[A[ind]] == 0) 
        ele.erase(A[ind]);
      
  
    // Restore A to original form.
    // (Backtracking step)
    swap(A[ind], B[ind]);
  
    // Increase count of A[i] in map and
    // call recursively for next index.
    ele[A[ind]]++;
    minCountUtil(A, B, ele, ans, ind + 1);
  
    // Restore the changes done
    // (Backtracking step)
    ele[A[ind]]--;
    if (ele[A[ind]] == 0) 
        ele.erase(A[ind]);    
}
  
// Function to find minimum number of
// distinct characters in string.
int minCount(string A, string B)
{
    // Variable to store minimum number
    // of distinct character.
    // Initialize it with length of A
    // as maximum possible value is
    // length of A.
    int ans = A.length();
  
    // Map to store count of distinct
    // characters in A. To keep
    // complexity of insert operation
    // constant unordered_map is used.
    unordered_map ele;
  
    // Call utility function to find
    // minimum number of unique
    // characters.
    minCountUtil(A, B, ele, ans, 0);
  
    return ans;
}
  
int main()
{
    string A = "abaaa";
    string B = "bbabb";
  
    cout << minCount(A, B);
    return 0;
}
输出:
2

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