22.最少字符串操作次数<字节青训营-中等题>

97 阅读1分钟

1.题目

问题描述

小U得到一个只包含小写字母的字符串 S。她可以执行如下操作:每次选择字符串中两个相同的字符删除,然后在字符串末尾添加一个任意的小写字母。小U想知道,最少需要多少次操作才能使得字符串中的所有字母都不相同?


测试样例

样例1:

输入:S = "abab"

输出:2

样例2:

输入:S = "aaaa"

输出:2

样例3:

输入:S = "abcabc"

输出:3

2.思路

每种字符需要删除的次数是这个字符的个数/2

3.代码

#include <iostream>
#include <string>
#include <map>
using namespace std;

int solution(const std::string& S) {
    // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
    // write code here
    map<char, int> cnt;
    for(char c : S) {
        cnt[c]++;
    }
    int result = 0;
    for (auto &pair : cnt) {
        result += pair.second / 2;
    }
    return result; 
}

int main() {
    std::cout << (solution("abab") == 2) << std::endl;
    std::cout << (solution("aaaa") == 2) << std::endl;
    std::cout << (solution("abcabc") == 3) << std::endl;
}