力扣-LCR 169. 招式拆解 II

文章目录

力扣题目

某套连招动作记作仅由小写字母组成的序列 arr,其中 arri 第 i 个招式的名字。请返回第一个只出现一次的招式名称,如不存在请返回空格。

示例 1:

输入:arr = "abbccdeff"

输出:'a'

示例 2:

输入:arr = "ccdd"

输出:' '

限制:

0 <= arr.length <= 50000

代码

使用到了自定义类型的map,如果有看不明白的可以参考map容器的使用,文章里边有自定义数据类型排序可以参考一下,易懂!

cpp 复制代码
class Index
{
public:
    Index(int index, int counts)
    {
        m_index = index;/*key值对应的索引*/
        m_counts = counts;/*key值元素在字符数组中出现的次数*/
    }

    int m_index;
    int m_counts;
};

class Solution {
public:
    char dismantlingAction(string arr) 
    {
        map<char, Index>m;/*创建一个自定义的类*/
        int minIndex = 60000;/*随便给出一个大于arr.length的值*/
        int flag = -1;/*标记用来确定是否返回空格字符*/
        char temp = 0;/*返回的字符*/
        for (int i = 0; i < arr.size(); i++)
        {
            map<char, Index>::iterator pos = m.find(arr[i]);
            if (pos != m.end())/*字符数组中的元素已经在容器m中存在*/
            {
                pos->second.m_counts++;/*更新出现次数*/
            }
            else 
            {
                m.insert(make_pair(arr[i], Index(i, 1)));
            }
        }
        
        for (map<char, Index>::iterator it = m.begin(); it != m.end(); it++)
        {
            if (1 == it->second.m_counts)/*判断arr中是否有只出现一次的数据*/
            {
                flag = 1;
                /*找到索引值小的元素,也就是题目中所说的返回第一个只出现一次的招式名称*/
                if (it->second.m_index < minIndex)
                {
                    minIndex = it->second.m_index;/*更新最小的索引值*/
                    temp = it->first;/*更新索引对应的字符值*/
                }          
            }
        }

        /*如果flag < 0说明arr中的元素都不符合条件,返回空格*/
        if (flag < 0)
        {
            return ' ';
        }

        return temp;
    }
};
相关推荐
旖-旎1 小时前
《LeetCode 416 分割等和子集》
c++·算法·leetcode·动态规划·背包问题
晚笙coding21 小时前
LeetCode 226. 翻转二叉树(Invert Binary Tree)
算法·leetcode·职场和发展
退休倒计时1 天前
【每日一题】LeetCode 287. 寻找重复数 TypeScript
算法·leetcode·typescript
G.O.G.O.G1 天前
《LeetCode SQL 从入门到精通(MySQL)》09
sql·mysql·leetcode
To_OC2 天前
LC 22 括号生成:刷完这道题,我终于搞懂回溯剪枝了
javascript·算法·leetcode
To_OC2 天前
LC 39 组合总和:回溯入门必刷题,我踩过的两个坑都在这了
javascript·算法·leetcode
兰令水2 天前
hot100【acm版】【2026.7.14打卡-java版本】
java·数据结构·算法·leetcode·面试
tachibana22 天前
hot100 课程表(207)
java·数据结构·算法·leetcode
旖-旎2 天前
《LeetCode 646 最长数对链 || LeetCode 1143 最长公共子序列》
c++·算法·leetcode·动态规划
Frostnova丶2 天前
(15)LeetCode 189. 轮转数组
数据结构·算法·leetcode