2315. 统计星号
解题思路
根据题意可知,我们只需要关心字符换中|
和*
即可,只需要记录双数|
后的*
的个数,我们使用一个flag标记来记录单双数,使用count来记录*
的个数,最后返回即可。
代码实现
public class Solution {
public int countAsterisks(String s) {
int count = 0;
boolean flag = true;
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c == '|') {
flag = !flag;
} else if (flag && c == '*') {
count++;
}
}
return count;
}
}
复杂度分析
- 时间复杂度
O(n)
,其中n是s的长度,只需要遍历s一遍。 - 空间复杂度
O(1)
,只需要常数空间。