力扣-LCR 169. 招式拆解 II

文章目录

力扣题目

某套连招动作记作仅由小写字母组成的序列 arr,其中 arr[i] 第 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;
    }
};
相关推荐
毅炼8 小时前
今日LeetCode 摸鱼打卡
java·算法·leetcode
m0_629494738 小时前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒8 小时前
力扣HOT100(25)环形链表
算法·leetcode·链表
Controller-Inversion12 小时前
76. 最小覆盖子串
java·算法·leetcode
_日拱一卒12 小时前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展
世纪末的小黑12 小时前
【LeetCode自用】LeetCode自用记录贴,题目一:两数之和
数据结构·算法·leetcode
兰令水12 小时前
topcode【随机算法题】【2026.5.22打卡-java版本】
java·算法·leetcode
水木流年追梦1 天前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式
始三角龙1 天前
LeetCode hoot 100 -- 缺失的第一个正整数
算法·leetcode·职场和发展
战南诚1 天前
力扣 之 198.打家劫舍
python·算法·leetcode