Leetcode brushing questions---string---student attendance record Ⅰ

Given a string to represent the attendance record of a student, this record only contains the following three characters:

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

If a student's attendance record does not exceed one'A' (absence) and no more than two consecutive'L's (late), then the student will be rewarded.

You need to judge whether this student will be rewarded based on his attendance record.

Example 1:

Input: "PPALLP"
Output: True

Example 2:

Input: "PPALLL"
Output: False

This question is very simple, just define an array directly to store the student attendance data.

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;
 
    }
}

In addition, the problem solution also uses the wording of indexof

The easiest way to solve this problem is to count the number of AAA in the string and check whether the LLL is a substring of the given string. If the number of A is less than 2 and LLL is not a substring of the given string, then return true, otherwise return false.

The indexOfindexOfindexOf method in Java can be used to check whether a string is a substring of another string. If the substring cannot be found, then -1 is returned, otherwise the position of the first occurrence of this string is returned.

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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Source: LeetCode
Link: https://leetcode-cn.com/problems/student-attendance-record-i The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_46428711/article/details/111340645