Noob v. LeetCode, episode 9, counting characters in strings

Joan Indiana Lyness
Oct 2 · 4 min read

For my next easy LeetCode challenge, I found this one, which involves finding occurrences of letters in a string:

Since I am trying to increase my JavaScript skills, I wanted to start there, but I could not resist Ruby, which really is way more intuitive for simple tasks like this.

We are trying to count how many times our S, or stones, string includes letters from J, our jewels string.

In Ruby:

Let’s set a counter: counter = 0

then split our J string into an array so we can iterate over the elements of the array easily:

array = j.split(‘’)

Next, we increment our counter each time it finds any of the array elements in our ‘s’ string:

array.each do |el|
counter += s.count(el)
end

Then we return the counter. All together:

def num_jewels_in_stones(j, s)
counter = 0
array = j.split('')

array.each do |el|
counter += s.count(el)
end
counter
end

Not bad! It’s quite fast and has super low memory usage:

If only javaScript were that easy …

Not going to lie. Using the same logic in js is a pain in the tush.

You still set a counter, and you still search for how many times S contains a character from J — but the syntax is clunkier.


var numJewelsInStones = function(J, S) {
let counter = 0;
// iterate here
return counter;
};

Here’s the basic pattern for iteration in JavaScript:

for (let i = 0; i < S.length; i++) {
if(J.indexOf(S.charAt(i)) !== -1)
counter++;
}

let’s unpack that.

  • In the first line, we set up a value ‘i’ so we can iterate through every character of the S string.
  • In the second line, we are checking to see if the character from S has an index in J (i.e. is it included in the J string). If it does, we increment our counter.
  • NOTE: if J does *not* include the character we’re looking for, the charAt() method will return -1. By saying if the character’s index is *not* equal to negative one, we are really saying, if the character is found. Sometimes this is also written as: if(J.indexOf(S.charAt(i)) ≥ 0 ). That is just a cleaner looking way of saying != -1 .

All together:

var numJewelsInStones = function(J, S) {
let counter = 0;
for (let i = 0; i < S.length; i++) {
if(J.indexOf(S.charAt(i)) !== -1)
counter++;
}
return counter;
};

Not too shabby:

Cleaning it up with forEach()

javaScript has a forEach() method which lets you skip the

for(let i= 0; i < array.length; i++) syntax.

The syntax is:

array.forEach(element => {
// do something with element
});

You cannot use it on strings, but you can split your string into an array and use it like so:

var numJewelsInStones = function(J, S) {
let counter = 0;
S.split('').forEach(element => {
J.indexOf(element) >= 0 ? counter ++ : counter
});
return counter;
};

Notice that on line 4, we are using a ternary operator: :

it works like this:

condition met ? do this : otherwise do that

This last function looks slightly cleaner, and has the same stats as the one before.

Speedy

If you really want to speed things up, you can try this one-liner from jssScripter:

const numJewelsInStones = (J, S) => S.split('').filter(char => J.indexOf(char) !== -1).length;

Let’s unpack that.

We’re still splitting the S string into an array. Only this time, we’re filtering it — for each character of S, we want to return that character if it is found in J (again, if its indexOf is not equal to -1). Once we’ve collected those characters, we count them with .length.

It’s a bit faster:

but notice, Ruby is way faster.

Ruby solution stats again:

next: Algorithms 101 #10, Birthday Chocolate in JavaScript

in case you missed it: Algorithms 101 #8, Best Time to Buy and Sell Stock in JavaScript

Copyright © Joan Indiana Lyness 2019

JavaScript in Plain English

Learn the web's most important programming language.

Joan Indiana Lyness

Written by

Hire me in Washington DC! Full-stack developer, Ruby, Rails, JavaScript, i love! React. https://joan-s-portfolio.firebaseapp.com/projects

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade