【LeetCode每日一题 / Java实现】2023-01-29 2315. 统计星号(简单)

文章目录

  • 题目链接
  • 题目大意
  • 答案一
  • 答案二 开关状态


题目链接

https://leetcode.cn/problems/count-asterisks/

题目大意

两个|为一对,统计竖线之外的*的个数

答案一

按照|分割成字符串数组,只取数组下标为0,2,4,....的内容,这些都是在一对|之外的,统计*出现的次数
【LeetCode每日一题 / Java实现】2023-01-29 2315. 统计星号(简单)_第1张图片

class Solution {
    public int countAsterisks(String s) {
        String[] split = s.split("\\|");
        int ans = 0;
        if (split.length != 0) {
            for (int i = 0; i < split.length; i += 2) {
                int len = split[i].length();
                for (int j = 0; j < len; j++) {
                    if (split[i].charAt(j) == '*') {
                        ans++;
                    }
                }
            }
        }
        return ans;
    }
}

答案二 开关状态

设置一个变量,来记录当前是否处于一对|之内

【LeetCode每日一题 / Java实现】2023-01-29 2315. 统计星号(简单)_第2张图片

class Solution {
    public int countAsterisks(String s) {
        boolean flag = true;
        int ans = 0;
        for (int i = 0; i < s.length(); i++) {
            if (flag && s.charAt(i) == '*') {
                ans++;
            }
            if (s.charAt(i) == '|') {
                flag = !flag;
            }
        }
        return ans;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,java,学习,字符串)