#Leetcode# 387. First Unique Character in a String

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

 

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.

代码:

class Solution {
public:
    int firstUniqChar(string s) {
        int len = s.length();
        unordered_map<char, int> mp;
        int ans = -1;
        
        for(int i = 0; i < len; i ++)
            mp[s[i]] ++;
        
        for(int i = 0; i < len; i ++) {
            if(mp[s[i]] == 1) {
                ans = i;
                break;
            }
        }
        return ans;
    }
};

  

FHFHFH

posted @ 2019-01-30 20:35  丧心病狂工科女  阅读(90)  评论(0编辑  收藏  举报