- Date : 2021.09.19(일)
- Time : 20분
- 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.
- Input: s = "loveleetcode"
- Output: 2
def firstUniqChar(self, s: str) -> int:
new_list = {}
for i in s:
try:
new_list[i] += 1
except:
new_list[i] = 1
for key, value in new_list.items():
if value == 1: return s.find(key)
return -1
: 이 문제는 중복되지 않은 문자 즉, 한번만 쓰인 문자를 찾는 것. 만약 한번만 쓰인 문자가 여러개라면 그 중 인덱스가 제일 앞에인 문자를 찾아서 인덱스를 return 하면 된다. 그래서 dict을 이용해 문제를 풀었다. 먼저 for 문을 이용해서 try, except 문을 사용했다. new_list에 i가 존재하면 try문, 아니라면 except 문이 실행된다. 그 이후 dict 형에서 key , value를 통해 value = 1인것을 찾았다. 이것은 1개의 문자만 있다는 것. 그러면 바로 return으로 인덱스를 찾아 반환해줬다. 이래야지 그 뒤에 더 찾지 않는 수고를 덜 수 있다.