力扣-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;
    }
};
相关推荐
blxr_2 小时前
力扣hot100爬楼梯https://leetcode.cn/problems/climbing-stairs/
算法·leetcode·职场和发展
Navigator_Z4 小时前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode
All for pursuit.6 小时前
【分治-2】215.数组中的第K个最大元素
数据结构·c++·算法·leetcode
blxr_7 小时前
力扣hot100前k个高频元素https://leetcode.cn/problems/top-k-frequent-elements/
算法·leetcode·职场和发展
longlongzihan17 小时前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
smj2302_796826521 天前
解决leetcode第4064题至多一次取反能被k整除的最长子数组II
python·算法·leetcode
青山木1 天前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
垆边人似月.1 天前
字符串重排后最大字典序
算法·leetcode·职场和发展
代码什么用1 天前
LeetCode-42. 接雨水
算法·leetcode
yi0111 天前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划