leetcode 387.字符串中第一个唯一字符

⭐️ 题目描述


🌟 leetcode链接:https://leetcode.cn/problems/first-unique-character-in-a-string/description/

思路: 比较优的方式使用相对映射记录的方式。在 ASCII 表中小写字母 -97 就是 0 - 25。在依次从前遍历查找即可。需要注意的是 :这里使用 char 数组不行 因为 char 数组每个元素最多只能存储到127 次,那如果超出 127 次就会溢出 所以用 int 精度比较高。

代码:

cpp 复制代码
class Solution {
public:
    int firstUniqChar(string s) {
        // 哈希
        int hash[26] = {0};
        /*
            这里使用 char 数组不行 因为char数组每个元素最多只能存储到127次
            那如果超出127次就会溢出 所以用 int 精度比较高
        */
        for (int i = 0; i < s.size(); i++) {
            hash[s[i] - 97]++;
        }

        // 查找
        for (int i = 0; i < s.size(); i++) {
            if (hash[s[i] - 97] == 1) {
                return i;
            }
        }

        return -1;
    }
};

相关推荐
君义_noip10 小时前
信息学奥赛一本通 1661:有趣的数列 | 洛谷 P3200 [HNOI2009] 有趣的数列
c++·算法·组合数学·信息学奥赛·csp-s
一起养小猫12 小时前
LeetCode100天Day14-轮转数组与买卖股票最佳时机
算法·leetcode·职场和发展
hele_two12 小时前
快速幂算法
c++·python·算法
OopspoO12 小时前
C++杂记——Name Mangling
c++
yuanmenghao12 小时前
车载Linux 系统问题定位方法论与实战系列 - 车载 Linux 平台问题定位规范
linux·运维·服务器·网络·c++
小羊羊Python13 小时前
SoundMaze v1.0.1正式发布!
开发语言·c++
程序员-King.13 小时前
day143—递归—对称二叉树(LeetCode-101)
数据结构·算法·leetcode·二叉树·递归
码小猿的CPP工坊16 小时前
C++软件开发之内存泄漏闭坑方法
开发语言·c++
Ethan-D16 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
Benny_Tang16 小时前
题解:CF2164C Dungeon
c++·算法