leetcode 387.字符串中第一个唯一字符
⭐️ 题目描述
🌟 leetcode链接:https://leetcode.cn/problems/first-unique-character-in-a-string/description/
思路:
比较优的方式使用相对映射记录的方式。在 ASCII
表中小写字母 -97
就是 0 - 25
。在依次从前遍历查找即可。需要注意的是:这里使用 char
数组不行 因为 char
数组每个元素最多只能存储到127
次,那如果超出 127
次就会溢出 所以用 int
精度比较高。
代码:
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;}
};