Skip to content

2315. Count Asterisks 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int countAsterisks(string s) {
    int ans = 0;
    int bars = 0;

    for (const char c : s) {
      if (c == '|')
        ++bars;
      else if (c == '*' && bars % 2 == 0)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int countAsterisks(String s) {
    int ans = 0;
    int bars = 0;

    for (final char c : s.toCharArray()) {
      if (c == '|')
        ++bars;
      else if (c == '*' && bars % 2 == 0)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def countAsterisks(self, s: str) -> int:
    ans = 0
    bars = 0

    for c in s:
      if c == '|':
        bars += 1
      elif c == '*' and bars % 2 == 0:
        ans += 1

    return ans