Skip to content
Advertisement

how to use python to find the first not repeating character?

I am solving a problem: Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return ‘_’.

For example: s = “abacabad”, the output should be firstNotRepeatingCharacter(s) = ‘c’.

I wrote a simple code, it got through all the test, but when I submit it, it reports error, anyone know what’s wrong with my code? Thank you!

JavaScript

Advertisement

Answer

Could be a performance issue as your repeated count (and unnecessary list conversions) calls make this approach quadratic. You should aim for a linear solution:

JavaScript

You can also use next with a generator and a default value:

JavaScript

If you can only use built-ins, just make your own counter (or any other data structure that allows you to identify duplicates)

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement