zoukankan      html  css  js  c++  java
  • LeetCode 387. 字符串中的第一个唯一字符 哈希

    地址 https://leetcode-cn.com/problems/first-unique-character-in-a-string/

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
    
    示例:
    s = "leetcode"
    返回 0
    
    s = "loveleetcode"
    返回 2
     
    
    提示:你可以假定该字符串只包含小写字母。

    使用哈希 map或者unordered_map

    或者直接使用int arr[26] 使用字母和'a'的差值作为索引 直接查表也是一种哈希的方案

    算法1
    哈希

    先记录每个字母出现的次数 然后找出第一个为出现1次的字母索引

    C++ 代码

    class Solution {
    public:
        map<char, int> mm;
        int firstUniqChar(string s) {
            for (int i = 0; i < s.size(); i++) {
                mm[s[i]]++;
            }
    
            //遍历字符串 查找哈希中出现的次数
            for (int i = 0; i < s.size(); i++) {
                if (mm[s[i]] == 1) return i;
            }
    
            return -1;
        }
    };
    
     

    算法2
    算法1的改进 使用了unordered_map 而不是 map 查找更快

    class Solution {
    public:
        unordered_map<char, int> mm;
        int firstUniqChar(string s) {
            for (int i = 0; i < s.size(); i++) {
                mm[s[i]]++;
            }
    
            //遍历字符串 查找哈希中出现的次数
            for (int i = 0; i < s.size(); i++) {
                if (mm[s[i]] == 1) return i;
            }
    
            return -1;
        }
    };
    
     

    算法3
    直接使用 int arr[26]的数组作为字母的哈希表
    字母与’a’的差值作为数组索引速度更快

    class Solution {
    public:
        int mm[26] = { 0 };
        int firstUniqChar(string s) {
            for (int i = 0; i < s.size(); i++) {
                int idx = s[i] - 'a';
                mm[idx]++;
            }
    
            //遍历字符串 查找哈希中出现的次数
            for (int i = 0; i < s.size(); i++) {
                int idx = s[i] - 'a';
                if (mm[idx] == 1) return i;
            }
    
            return -1;
        }
    };
    
     

  • 相关阅读:
    CSS实现雨滴动画效果
    大型网站架构系列:电商网站架构案例
    CSS 不定宽高的垂直水平居中方式总汇
    js中尺寸类样式
    Tiling
    排序二叉树
    算术表达式的转换
    Area
    catch that cow
    R中双表操作学习[转载]
  • 原文地址:https://www.cnblogs.com/itdef/p/14176825.html
Copyright © 2011-2022 走看看