【14】387. First Unique Character in a String

387. First Unique Character in a String

Total Accepted: 41662

  • Total Submissions: 91486
  • Difficulty: Easy
  • Contributors: Admin

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.

 1 class Solution {
 2 public:
 3     int firstUniqChar(string s) {
 4         unordered_map<char, int> hash;
 5         for(char c : s){
 6             hash[c]++;
 7         }
 8         /*
 9         for(int i : hash){
10             if(i == 1)
11         }*///没法从hash表里判断,因为只知道value不能逆向得知hash里面的key
12         //所以要从原string里找
13         for(int i = 0; i < s.size(); i++){
14             if(hash[s[i]] == 1){
15                 return i;
16             }
17         }
18         return -1;
19     }
20 };

 

 

 

 

 

 

 

 

 

posted @ 2017-02-04 08:40  会咬人的兔子  阅读(125)  评论(0编辑  收藏  举报