leetcode刷题---字符串---学生出勤记录Ⅰ

给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:

'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场

如果一个学生的出勤记录中不超过一个’A’(缺勤)并且不超过两个连续的’L’(迟到),那么这个学生会被奖赏。

你需要根据这个学生的出勤记录判断他是否会被奖赏。

示例 1:

输入: “PPALLP”
输出: True

示例 2:

输入: “PPALLL”
输出: False

这题很简单,直接定义一个数组来存放数据学生出勤数据即可。

class Solution {
    
    
    public boolean checkRecord(String s) {
    
    
        int[] alp = new int[3];
        int leng = s.length();

        for(int i=0;i<leng;i++){
    
    
            if(s.charAt(i) == 'A'){
    
    
                alp[0]++;
                if(alp[0]>1)return false;
            }
            if(s.charAt(i) == 'L'){
    
    
                if(i<leng-2){
    
    
                    if(s.charAt(i+1)== 'L'&&s.charAt(i+2)== 'L')return false;
                }
            }
        }
        return true;
 
    }
}

此外题解还有用到了indexof的写法

解决这个问题最简单的方法就是统计字符串中 AAA 的数目并检查 LLL 是否是给定字符串的一个子串。如果 A的数目比 2 少且 LLL 不是给定字符串的一个子串,那么返回 true,否则返回 false。

Java 中indexOfindexOfindexOf 方法可以用来检查一个串是否是另一个串的子串。如果找不到子串,那么返回 -1,否则返回这个字符串第一次出现的位置。

public class Solution {
    
    
    public boolean checkRecord(String s) {
    
    
        int count=0;
        for(int i=0;i<s.length() && count<2 ;i++)
            if(s.charAt(i)=='A')
                count++;
        return count<2 && s.indexOf("LLL")<0;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/student-attendance-record-i/solution/xue-sheng-chu-qin-ji-lu-i-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/student-attendance-record-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/weixin_46428711/article/details/111340645