작심삼일

[LeetCode] 387 | First Unique Character in a String | Python 본문

스터디/코테

[LeetCode] 387 | First Unique Character in a String | Python

yun_s 2022. 8. 16. 20:17
728x90
반응형

문제 링크: https://leetcode.com/problems/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.


조건

  • 1 <= s.length <= $10^5$
  • s consists of only lowercase English letters.

내 풀이

 


코드 

class Solution:
    def firstUniqChar(self, s: str) -> int:
        unique, common = {}, []
        
        for idx, char in enumerate(s):
            if char not in unique and char not in common:
                unique[char] = idx
            elif char in unique:
                common.append(char)
                unique.pop(char)
        
        return unique[list(unique.keys())[0]] if unique.keys() else -1
728x90
반응형
Comments