Leetcode刷题82-551. 学生出勤记录 I(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/student-attendance-record-i/]

1.Question

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

2.Answer

easy 类型题目。
我的暴力解题思路

  1. 统计 ‘A’ 和 ‘L’ 出现的次数,分别用 a 和 b 表示。
  2. 若 a <= 1 && b <=2 返回true。
  3. 若 a <= 1 && b > 2 ,则继续 判断 有没有 三个连续的 ‘L’,如果有三个连续的,则返回 false,没有三个连续的则返回 true。
  4. 若 a > 1 ,返回 false。

AC代码如下:(比较low。。。)

class Solution {
public:
    bool checkRecord(string s) {
        int a = 0;
        int b = 0;
        bool ok = true;
        for(auto c : s)
        {
            if(c == 'A')
            {
                ++a;
            }
            if(c == 'L')
            {
                ++b;
            }
        }
        if(a <= 1 && b <= 2)
        {
            ok = true;
        }
        else if(a <= 1 && b > 2)
        {
            for(int i = 0; i < s.size() - 2; ++i)
            {
                if(s[i] == 'L')
                {
                    if(s[i+1] == 'L')
                    {
                        if(s[i+2] == 'L')
                        {
                            ok = false;
                        }
                    }
                }
            }
        }
        else
        {
            ok = false;
        }
        return ok;
        
    }
};

3.大神们的解决方案

排名第一的 解法。。。比我的简洁啊 啊 啊。。。
AC代码如下:

class Solution {
public:
    bool checkRecord(string s) {
        int countA = 0, countL = 0;
        for(size_t i = 0; i < s.size(); ++i)
        {
            if(s[i] == 'L')
            {
                countL++;
                if(countL > 2)
                    return false;
                continue;
            }
            countL = 0;
            if(s[i] == 'A')
            {
                countA++;
                if(countA > 1)
                    return false;
            }
        }
        
        return true;
    }
};

4.我的收获

Fighting~~~

2019/5/19 胡云层 于南京 82

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值