统计星号【LC2315】
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.
带侄子去医院 又错过周赛了 哎
- 思路:记录每个'|'的编号,统计第偶数个'|'之后、第奇数个'|'之前的星号,以及末尾剩余字符串的星号个数
- 实现
class Solution { public int countAsterisks(String s) { int ans = 0; int count = 0; int idx = 0; for (char c : s.toCharArray()){ if (c == '*'){ count++; }else if(c == '|'){ idx++; if (idx % 2 == 1){ ans += count; } count = 0; } } return ans + count; } }
。复杂度
- 时间复杂度:O ( n ) ,n 为字符串的长度
- 空间复杂度:O ( 1 )