1. 程式人生 > >LeetCode Student Attendance Record I 學生出勤記錄I

LeetCode Student Attendance Record I 學生出勤記錄I

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