【leetcode】387 字符串中的第一个唯一字符(字符串)

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

题目描述

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

代码

class Solution {
public:
    int firstUniqChar(string s) {
        int m[256];
        // -1 代表没有出现过
        // -2  代表出现多次
        // >=0 代表只出现1次,该数字代表出现的位置
        for (int j = 0; j < 256; ++j)
            m[j] = -1;

        for (int i = 0; i < s.size(); ++i) {
            if(m[s[i]] == -1)
                m[s[i]] = i;
            else if(m[s[i]]>=0)
                m[s[i]] = -2;
        }
        
        int minIndex = s.size();
        for (int k = 0; k < 256; ++k) {
            if(m[k]>=0 && m[k] < minIndex)
                minIndex = m[k];
        }
        return minIndex == s.size()?-1:minIndex;
    }
};

猜你喜欢

转载自blog.csdn.net/zjwreal/article/details/89707424