2023-01-13【c++】【Leecode】2287. 重排

2023-01-12  本文已影响0人  持刀的要迟到了

2287. 重排字符形成目标字符串 - 力扣(LeetCode)

class Leecode
{
public:
    int rearrangeCharacters(string s, string target)
    {
        int sLen = s.length();
        int tarLen = target.length();

        const char* sArr = s.c_str();
        const char* tarArr = target.c_str();

        // key:target唯一char value[0]:target唯一char需要个数 value[1]:s拥有唯一char个数
        map<char, int*> matchMap;
        // 根据target初始化数据结构
        for (size_t i = 0; i < tarLen; ++i)
        {
            char curChar = target[i];
            map<char, int*>::iterator pair = matchMap.find(curChar);
            if (pair == matchMap.end())
            {// 不存在
                int* toAdd = new int[2]{ 1, 0 };
                matchMap[curChar] = toAdd;
            }
            else
            {// 存在
                matchMap[curChar][0]++;
            }
        }

        // 根据s向字典表中塞入
        for (size_t i = 0; i < sLen; ++i)
        {
            char curChar = sArr[i];
            map<char, int*>::iterator pair = matchMap.find(curChar);
            if (pair == matchMap.end())
            {// 不存在
            }
            else
            {// 存在
                matchMap[curChar][1]++;
                continue;
            }
        }

        // 遍历字典表,value的0和1取余,得到最小余数返回
        int minCount = -1;
        for (map<char, int*>::iterator it = matchMap.begin(); it != matchMap.end(); ++it)
        {
            int* value = it->second;
            int charCount = value[1] / value[0];
            if (minCount == -1)
            {
                minCount = charCount;
            }
            else
            {
                if (charCount < minCount)
                {
                    minCount = charCount;
                }
            }
        }

        return minCount;
    }

};
上一篇 下一篇

猜你喜欢

热点阅读