力扣-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;
    }
};
相关推荐
_Itachi__8 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
chao_7899 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
编程绿豆侠11 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
dying_man20 小时前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel20 小时前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
GGBondlctrl21 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想
枫景Maple1 天前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode