统计星号【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
'*'ins, 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)O(n)O(n),nnn为字符串的长度
- 空间复杂度:O(1)O(1)O(1)
- 复杂度

本文介绍了一种算法,用于统计字符串中特定位置的星号数量,即不在每对竖线之间的星号。通过遍历字符串并跟踪竖线的位置来实现这一目标。
1万+

被折叠的 条评论
为什么被折叠?



