-->

Friday, February 17, 2017

[LeetCode] 387. First Unique Character in a String

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

Solution:
This is an easy level question. We may use the hash map to count the time of appearances for  each element. Then find the first element with count number of 1 (or the total number of this kind of element is 1). Since all the letters are in lower case, we can use a 26-letter long vector, instead of a hashmap. See code below.

Code:
  1. class Solution {
  2. public:
  3.     int firstUniqChar(string s) {
  4.         int res = -1, n = s.size();
  5.         vector<int> count(26, 0);
  6.         for(auto a:s) ++count[a-'a'];
  7.         for(int i=0; i<n; ++i){
  8.             if(count[s[i]-'a'] == 1) {
  9.                 res = i;
  10.                 break;
  11.             }
  12.         }
  13.         return res;
  14.     }
  15. };

No comments :

Post a Comment