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

相关推荐
m0_748233173 小时前
30秒掌握C++核心精髓
开发语言·c++
风清扬_jd4 小时前
libtorrent-rasterbar-2.0.11编译说明
c++·windows·p2p
u0109272714 小时前
C++中的RAII技术深入
开发语言·c++·算法
彷徨而立4 小时前
【C/C++】strerror、GetLastError 和 errno 的含义和区别?
c语言·c++
誰能久伴不乏5 小时前
【Qt实战】工业级多线程串口通信:从底层协议设计到完美收发闭环
linux·c++·qt
2401_832131955 小时前
模板错误消息优化
开发语言·c++·算法
金枪不摆鳍5 小时前
算法--二叉搜索树
数据结构·c++·算法
liu****5 小时前
4.Qt窗口开发全解析:菜单栏、工具栏、状态栏及对话框实战
数据库·c++·qt·系统架构
近津薪荼5 小时前
优选算法——双指针6(单调性)
c++·学习·算法
helloworldandy5 小时前
高性能图像处理库
开发语言·c++·算法