Skip to content
Snippets Groups Projects
Commit 2550a183 authored by John bedingfield's avatar John bedingfield
Browse files

387 solved using dictionary

parent 183dbd0e
No related branches found
Tags v1.1.0
No related merge requests found
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 17 12:08:03 2022
@author: johnb aka John Bedingfield
"""
# this is for LeetCode #387, FIrst Unique Character in a String
# this was accepted
# runtime: 129 ms, faster than 68.27% of python3 submissions
# memory: 14.2MB, less than 20.47% of python3 submissions
class Solution:
def firstUniqChar(self, s: str) -> int:
counts = {} # dictionary to hold a count of each letter
# loop throught the string and get a count of each letter
for c in s:
if c not in counts:
counts[c] = 1
else:
counts[c] = counts[c] + 1
#print(counts)
# loop through the string and determine which char only has a count of 1
index = 0
for c in s:
if counts[c] == 1:
return index
else:
index += 1
# if we made it through with no answer,
return -1
if __name__ == "__main__":
s = "leetcode"
s2 = "loveleetcode"
s3 = "aabb"
myS = Solution()
starttime = int(time())
print(myS.firstUniqChar(s3))
endtime = int(time())
totalTime = endtime - starttime
print(f"Total time was {totalTime}")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment