2315.统计星号
链接:2315.统计星号
难度:Easy
标签:字符串
简介:请你返回 不在 竖线对之间,s 中 '*' 的数目。
题解 1 - typescript
- 编辑时间:2023-01-29
- 执行用时:68ms
- 内存消耗:43.9MB
- 编程语言:typescript
- 解法介绍:同上。
function countAsterisks(s: string): number {
        return s.split('|').filter((_, i) => i % 2 === 0).reduce((sum, cur) => sum + cur.split('').filter(v => v === '*').length, 0)
    };
题解 2 - cpp
- 编辑时间:2023-01-29
- 执行用时:4ms
- 内存消耗:6.5MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    int countAsterisks(string s) {
        istringstream iss(s);
        string tmp;
        int ans = 0;
        for (int i = 0; getline(iss, tmp, '|'); i++) {
            if (i % 2 == 0) 
                for (auto &c : tmp) if (c == '*') ans++;
        }
        return ans;
    }
};
题解 3 - python
- 编辑时间:2023-01-29
- 执行用时:48ms
- 内存消耗:15MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def countAsterisks(self, s: str) -> int:
        list = s.split('|')
        ans = 0
        for i in range(len(list)):
            if i % 2 == 0:
                for c in list[i]:
                    if c == '*':
                        ans += 1
        return ans
题解 4 - rust
- 编辑时间:2023-01-29
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn count_asterisks(s: String) -> i32 {
        let list = s.split('|').collect::<Vec<_>>();
        let mut ans = 0;
        for i in 0..list.len() {
            if i % 2 == 0 {
                for c in list[i].chars() {
                    if c == '*' {
                        ans += 1
                    }
                }
            }
        }
        ans
    }
}