Leet Code — 2315. Count Asterisks
Ben Pereira
Posted on August 29, 2023
It’s an easy problem from leet code with the description being:
You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.
Return the number of '' in s, excluding the '' between each pair of '|'.
Note that each '|' will belong to exactly one pair.
Example 1:
Input: s = "l|e*et|co|*de|"
Output: 2
Explanation: The considered characters are underlined: "l|*e*et|c*o|*de|".
The characters between the first and second '|' are excluded from the answer.Also, the characters between the third and fourth '|' are excluded from the answer.
There are 2 asterisks considered. Therefore, we return 2.
Example 2:
Input: s = "iamprogrammer"
Output: 0
Explanation: In this example, there are no asterisks in s. Therefore, we return 0.Example 3:
Input: s = "yo|uar|e*|b|eau|tifu|l"
Output: 5
Explanation: The considered characters are underlined: "yo|uar|e|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5.Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters, vertical bars '|', and asterisks '*'.
s contains an even number of vertical bars '|'.
At first glance one way to get it done would be splitting the String using the vertical bars then ignoring every odd one and counting the asterisks, but actually you don’t need to do that, you can just iterate the String and count straight away (either counting the bars or using a Boolean to validate).
class Solution {
public int countAsterisks(String s) {
int counter = 0;
boolean notIgnore = true; // flag that will swap when vertical bar found
for(int i=0 ; i<s.length() ; i++) {
// retrieving char
char c = s.charAt(i);
// ignoring the ones not needed
if(c != '*' && c != '|') continue;
// checking if is asterisk and to be ignored or not
if(c == '*') {
if(notIgnore) counter++;
} else {
notIgnore = !notIgnore;
}
}
return counter;
}
}
Runtime: 2 ms, faster than 71.32% of Java online submissions for Count Asterisks.
Memory Usage: 40.7 MB, less than 37.11% of Java online submissions for Count Asterisks.
Another case that can be done is use of regular expression and replacement, but that would be overkill for an easy problem, unless you want to bring to the next level, imo.
That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.
Until next post! :)
Posted on August 29, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.