387. 字符串中的第一个唯一字符

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

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

1.原创

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map <char,int> temp;

        
        for(int i=0;i<s.length();++i){
            ++temp[s[i]];
        }
        for (int i=0;i<s.length();++i){
            if (temp[s[i]]==1)
                return i;
        }
        return -1;
    }
};

2.题解

//如果不允许用额外空间,可以两头查找s[i]的位置,比较是否相同,若是则返回i,遍历完好
class Solution {
public:
    int firstUniqChar(string s) {
        if (s.empty()) {
            return -1;
        }

       for (int i = 0; i < s.size(); i++) {
           if (s.find(s[i]) == s.rfind(s[i])) {
               return i;
           }
       }

       return -1;
    }
};

作者:jyj407
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/zhong-gui-zhong-ju-387-zi-fu-chuan-zhong-p1zp/
原文地址:https://www.cnblogs.com/USTC-ZCC/p/14504822.html