Find the first non-repeating character

Find the first non-repeating character

Today we are given a string of characters, the task is to return the first non-repeating character in the string. For the purposes of repetition upper case and lower case characters are treated as the same character but the returned value must have the correct case.

Example

'stress' => t 'sTress' => T
Code language: PHP (php)

If there are no non-repeating characters, then return an empty string.

Let’s find it

The title might as well be the code. The idea is to find the first character that meets our requirements. The find method does all three when given the correct callback.

So the only part that needs two brain cells is the callback.

const getFirst = (s) => { const ret = s.split("").find(char => { const re = new RegExp(`${char}`,"ig"); return s.match(re).length === 1 }) return ret || '' }
Code language: JavaScript (javascript)

Our callback checks each character to see if it is repeating, if it isn’t it returns true. We have to be careful of the find function though because if it doesn’t find anything it returns undefined.

Otherwise, I don’t really have too much to say here. It’s a simple problem with a simple solution. If you have any questions about this one or just want to shoot the breeze, hit me up on Twitter @phoexer, and as always happy codding.


Leave a Reply

Your email address will not be published.