Leetcode 2315. Count Asterisks
You have a string s that consists of lower case English letters and symbols. The symbols are "*" and "|". We call a pair of bars a “barrier”. A pair of barriers divides the string into parts. Asterisks between consecutive bars are ignored, whereas those outside any barrier are counted.
You need to implement a function countAsterisks that accepts a string s and returns the total number of asterisks outside all the barriers.
s?
|?
| has a corresponding closing |.| symbols.Initialize Counters: Initialize a counter to keep track of the asterisks outside barriers and a flag to indicate whether we are inside a barrier section or not.
|.public class Solution {
public int countAsterisks(String s) {
int asteriskCount = 0;
boolean insideBarrier = false;
for (char c : s.toCharArray()) {
if (c == '|') {
insideBarrier = !insideBarrier;
} else if (c == '*' && !insideBarrier) {
asteriskCount += 1;
}
}
return asteriskCount;
}
}
n is the length of the string:
This solution is efficient given the constraints and handles all edge cases specified in the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?