387. First Unique Character in a String*

387. First Unique Character in a String*

https://leetcode.com/problems/first-unique-character-in-a-string/description/

题目描述

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

s = "leetcode"
return 0.


s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

解题思路

使用数组 vector<int> records(26, 0) 来统计每个字母个数, 然后再遍历字符串, 找到第一个不存在重复字母的字符.

C++ 实现 1

class Solution {
public:
    int firstUniqChar(string s) {
    	 // 如果不只是小写字母, 那么就设置为 256
        vector<int> records(26, 0);
        for (auto &c : s) records[c - 'a'] += 1;
        for (int i = 0; i < s.size(); ++i)
            if (records[s[i] - 'a'] == 1)
                return i;
        return -1;
    }
};

C++ 实现 2

看看两年前的思路…

由于可以认为字符串中只含有小写字母, 那么可以使用大小为 vector<int>(26, 0) 的数组保存字符的索引(如果不是小写字母, 那么就使用 vector<int>(256, 0)). 为什么保存索引能成功呢? 因为索引都是正数, 如果遇到重复的字符, 我就把索引设置为负数, 那么之后只要遍历一遍数组, 专门处理值大于 0 的值, 就可以找到最小的索引. 这里需要注意的是索引 0, 如果数组初始化为 -1, 可以避免这个尴尬. 当然也可以初始化为 0.

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

        vector<int> records(26, 0);

        for (int i = 0; i < s.size(); ++i) {
            int index = s[i] - 'a';
            if (records[index] == 0)
                records[index] = i + 1; // 保存索引+1, 以免和 0 误会
            else if (records[index] > 0)
                records[index] = -1; // 如果有重复, 就设置为 -1.
        }
        int first = INT32_MAX;
        for (const auto &index : records) {
            if (index > 0)
                first = min(first, index);
        }

        if (first == INT32_MAX)
            return -1;
        return first - 1; // 最后要减 1
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值