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;
    }
};

相关推荐
木心爱编程5 小时前
Qt C++ + OpenCV 实战:从零搭建实时视频滤镜与图像识别系统
c++·qt·opencv
Aspect of twilight5 小时前
LeetCode华为2025年秋招AI大模型岗刷题(四)
算法·leetcode·职场和发展
有泽改之_12 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER12 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
长安er12 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢13 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
CoderYanger13 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节
咕咕嘎嘎102413 小时前
C++六个默认成员函数
c++
菜鸟233号14 小时前
力扣513 找树左下角的值 java实现
java·数据结构·算法·leetcode
亭上秋和景清14 小时前
指针进阶:函数指针详解
开发语言·c++·算法