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

相关推荐
-dzk-1 天前
【代码随想录】LC 59.螺旋矩阵 II
c++·线性代数·算法·矩阵·模拟
m0_706653231 天前
C++编译期数组操作
开发语言·c++·算法
qq_423233901 天前
C++与Python混合编程实战
开发语言·c++·算法
TracyCoder1231 天前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode
m0_715575341 天前
分布式任务调度系统
开发语言·c++·算法
CSDN_RTKLIB1 天前
简化版unique_ptr说明其本质
c++
naruto_lnq1 天前
泛型编程与STL设计思想
开发语言·c++·算法
踩坑记录1 天前
leetcode hot100 94. 二叉树的中序遍历 easy 递归 dfs
leetcode
m0_748708051 天前
C++中的观察者模式实战
开发语言·c++·算法
时光找茬1 天前
【瑞萨AI挑战赛-FPB-RA6E2】+ 从零开始:FPB-RA6E2 开箱测评与 e2 studio 环境配置
c++·单片机·边缘计算