zoukankan      html  css  js  c++  java
  • leetcode-551-Student Attendance Record 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

     

    要完成的函数:

    bool checkRecord(string s)

    说明:

    1、这道题给定一个字符串,其中只有三种字符P/L/A,分别代表在场/迟到/缺席。如果一个学生出现了一次以上的缺席,或者连续两次以上的迟到,那么他就不能被奖励。要求判断是否某个学生能被奖励。

    2、关于A的,很容易,遍历一遍字符串统计A出现次数,当次数大于1时,返回false,结束遍历。

    关于L的,也不难,遍历一遍字符串,当碰到L时,判断下一个字符和再下一个字符是否均为L,如果满足,返回false,结束遍历(这里要注意边界条件,即下一个字符是否在字符串以内);如果不满足,那么继续处理下一个字符。

    代码如下:

        bool checkRecord(string s) 
        {
            int counta=0,countl=0;
            int s1=s.size();
            for(int i=0;i<s1;i++)
            {
                if(s[i]=='A')
                {
                    counta++;
                    if(counta>1)
                        return false;
                }
                else if(s[i+2]=='L'&&s[i+1]=='L'&&s[i]=='L')
                {
                    if(i+2<s1)
                        return false;
                }
            }
            return true;
        }

    上述代码实测6ms,beats 70.11% of cpp submissions。

    3、另一种方法

    参考了讨论区的代码实现,发现了另一种实际花费时间更少的方法。

    代码同样分享给大家,如下:

        bool checkRecord(string s) 
        {
            int counta=0,countl=0;
            for(int i = 0;i < s.size();i++)
            {
                if(s[i]=='A')
                {
                    counta++;
                    countl=0;//清空countl,重新开始
                    if(counta>1)
                        return false;
                }
                else if(s[i]=='L')
                {
                    countl++;
                    if(countl>2)
                        return false;
                } 
                else 
                    countl=0;
            }
            return true;
        }    

    上述代码实测4ms,beats 100% of cpp submissions。

    这样写代码看起来更加“清爽”,判断是否出现了连续的几个相同字符,采用的是碰到其他字符就“清空”的方法。

    而2中的方法,是碰到‘L’时继续判断下一个以及再下一个字符是否仍是'L'的方式,这种方法不需要引进countl的频繁计算。

    笔者还是更加喜欢“清爽”的代码,当L出现几百次才要return false的时候,明显清爽代码更省时间。

    这道题目给予的启示是:当要判断字符是否连续出现时,可以采用“清空”的方法来做。

  • 相关阅读:
    今天的收获
    【转载】sourceinsight使用技巧
    我的第一份工作
    IBatis的使用
    Struts2学习笔记(十九) 验证码
    Struts2学习笔记(十七) 文件下载(File Download)
    Struts2学习笔记(十六) 文件上传(File Upload)
    Struts2学习笔记(十八) 防止表单重复提交
    Struts2学习笔记(十四) 输入校验(下)
    Struts2学习笔记(十一) 类型转换(Type Conversion)(上)
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8984985.html
Copyright © 2011-2022 走看看