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

相关推荐
yunhuibin17 分钟前
无锁化编程——c++内存序使用
c++
zzzyyy5382 小时前
C++之vector容器
开发语言·c++
小安同学iter4 小时前
SQL50+Hot100系列(11.9)
算法·leetcode·职场和发展
uotqwkn89469s4 小时前
如果Visual Studio不支持C++14,应该如何解决?
c++·ide·visual studio
Maple_land5 小时前
Linux复习:冯·诺依曼体系下的计算机本质:存储分级与IO效率的底层逻辑
linux·运维·服务器·c++·centos
ue星空5 小时前
UE核心架构概念
网络·c++·ue5
ShineWinsu7 小时前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
_OP_CHEN7 小时前
C++进阶:(五)map系列容器的全面解析
开发语言·c++·map·红黑树·stl容器·键值对·mapoj题
hetao17338377 小时前
ZYZ28-NOIP模拟赛-Round4 hetao1733837的record
c++·算法
大米粥哥哥7 小时前
c++ libcurl报错Send failed since rewinding of the data stream failed【已解决】
开发语言·c++·http·curl·rewind