N

(Leet Code c++)FIrst Unique Character in a string 본문

Leet Code 알고리즘

(Leet Code c++)FIrst Unique Character in a string

naeunchan 2021. 8. 16. 10:06
728x90
반응형

387. First Unique Character in a String

 

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = "leetcode" Output: 0

Example 2:

Input: s = "loveleetcode" Output: 2

Example 3:

Input: s = "aabb" Output: -1

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.
class Solution {
public:
    int firstUniqChar(string s) {
        vector<vector<int>> check(26);
        
        for(int i = 0; i < s.size(); i++){
            check[s[i] - 'a'].push_back(i);
        }
        
        for(int i = 0; i < s.size(); i++){
            if(check[s[i] - 'a'].size() == 1){
                return check[s[i] - 'a'][0];
            }
        }
        
        return -1;
    }
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code JS)Roman to Integer  (0) 2021.08.25
(Leet Code c++)LRU Cache  (0) 2021.08.23
(Leet Code c++)3Sum  (0) 2021.08.10
(Leet Code c++)Ransom Note  (0) 2021.08.10
(Leet Code c++)Cuess Number Higher or Lower  (0) 2021.08.09