【LeetCode-字符串】字符串中的第一个唯一字符

题目描述

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

题目链接: https://leetcode-cn.com/problems/first-unique-character-in-a-string/

思路

使用哈希表来做。先遍历字符串一遍,统计每个字母出现的次数。因为题目要求找到第一个不重复的字符,所以,接下来还是从头遍历字符串(不是遍历哈希表),找到第一个出现次数为 1 的字母,否则返回 -1.

代码如下:

class Solution {
public:
    int firstUniqChar(string s) {
        if(s.empty()) return -1;

        vector<int> hash(26, 0);
        for(int i=0; i<s.size(); i++) hash[s[i]-'a']++;
        
        for(int i=0; i<s.size(); i++){
            if(hash[s[i]-'a']==1) return i; 
        }
        return -1;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
原文地址:https://www.cnblogs.com/flix/p/13325888.html