力扣-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;
    }
};
相关推荐
Tisfy6 分钟前
LeetCode 1291.顺次数:打表/枚举
算法·leetcode·题解·枚举·遍历
罗超驿1 小时前
双指针算法详解:从入门到精通(Java版)
算法·leetcode·职场和发展
tkevinjd1 小时前
力扣300-最长递增子序列
算法·leetcode·职场和发展·动态规划·贪心
tkevinjd5 小时前
416分割等和子集
java·python·算法·leetcode·职场和发展
什巳17 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
鱼儿也有烦恼19 小时前
快速学完 LeetCode top 1~50
leetcode·algorithm
退休倒计时1 天前
【每日一题】LeetCode 17. 电话号码的字母组合 TypeScript
算法·leetcode·typescript
临沂堇1 天前
刷题日志 | LeetCode Hot 100 双指针
算法·leetcode·职场和发展
XWalnut1 天前
LeetCode刷题 day29
java·算法·leetcode
小欣加油1 天前
leetcode1331 数组序号转换
数据结构·c++·算法·leetcode·职场和发展