LC 387. 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.

参考答案

 1 class Solution {
 2 public:
 3     int firstUniqChar(string s) {
 4 
 5         int count[26] = {0};
 6         for(char c:s){
 7             count[c-'a']++;
 8         }
 9         for(size_t i = 0; i<s.size();i++){
10             if(count[s[i] - 'a'] == 1) return i;
11         }
12         return -1;
13         
14         /*
15         unordered_map<char,int> map;
16         int min = 0;
17         
18         for(size_t i = 0 ; i < s.length();++i){
19             if(map.count(s[i])>0){
20                 map[s[i]] = -1;
21             }else{
22                 map[s[i]] = i;
23             }
24         }
25         for(size_t i = 0 ; i < s.length();++i){
26             if(map[s[i]] != -1){
27                 return map[s[i]];
28             }
29         }
30         return -1;*/
31         }
32 };

补充说明

第一次自己想出了accepted的答案,虽然和第一名的大佬差了很多,但是感觉还是很兴奋的。

答案中,使用了 count [ c - 'a' ] ,巧妙地将字母表示成为index。

posted @ 2019-10-02 01:11  schaffen  阅读(110)  评论(0编辑  收藏  举报