LeetCode Student Attendance Record I 学生出勤记录I

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sun_wangdong/article/details/82981684

You are given a string representing an attendance record for a student. The record only contains the following three characters:

  1. 'A' : Absent.
  2. 'L' : Late.
  3. 'P' : Present.

A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

You need to return whether the student could be rewarded according to his attendance record.

Example 1:

Input: "PPALLP"
Output: True

Example 2:

Input: "PPALLL"
Output: False

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

  1. 'A' : Absent,缺勤
  2. 'L' : Late,迟到
  3. 'P' : Present,到场

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

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

示例 1:

输入: "PPALLP"
输出: True

示例 2:

输入: "PPALLL"
输出: False

题解:给定一个字符串,如果该字符串中有不超过一个A(缺勤)并且不超过两个连续的L(迟到),那么该学生就会被奖励。此题是一道典型的字符串的题目,一拿到题目,如果遍历一下,那么比较费时间,所以就想到可不可以用正则表达式来解决。根据题目,如果字符串中不超过一个A(缺勤)并且不超过两个连续的L(迟到),那么才会被奖励;反之,如果该字符串中有2个及以上的A或有超过两个连续的L(迟到),那么就不会被奖励。所以寻着这个思路,首先可以用正则表达式去搜寻是否该字符串的子串中存在有连续的3个及以上的L(迟到);或者去查找该字符串是否有2个及以上的A。不过这里遇到了坑,就是直接用String.matches()去匹配,会使用出现false,后来查找资料才直到,String.matches()该方法只能去匹配整个字符串,而不能按照字符串中的子串匹配;所以,这里不能用String.matches()方法,只能通过Pattern和Matcher来实现。

1、对于匹配连续的3个及以上的L(迟到)

Pattern p1 = Pattern.compile("(LLL)+");
Matcher m1 = p1.matcher(s);
if(m1.find())
    return false;

表示去匹配一个字符串及子串中的3个及以上的L,用m1.find()来查找是否存在符合该正则匹配的字符串。

2、对于字符串中出现A 2个及以上

这个是寻找字符串中出现的A,那么这里不能用find,因为find只是寻找一次,而不负责寻找第二次,要寻找具体出现的次数,得用while循环去查找满足该正则匹配,所出现的次数。

    public static boolean checkRecord(String s)
    {
        if(s == null)
            return true;
        Pattern p1 = Pattern.compile("(LLL)+");
        Matcher m1 = p1.matcher(s);
        if(m1.find())
            return false;
        Pattern p2 = Pattern.compile("A");
        Matcher m2 = p2.matcher(s);
        int sum = 0;
        while(m2.find())
        {
            sum++;
            if(sum >= 2)
                return false;
        }
        return true;
    }

猜你喜欢

转载自blog.csdn.net/sun_wangdong/article/details/82981684
今日推荐