美文网首页LeetCode By Go
[LeetCode By Go 58]551. Student

[LeetCode By Go 58]551. Student

作者: miltonsun | 来源:发表于2017-08-25 16:11 被阅读4次

    题目

    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',如果是,则累计'A'的数量,如果‘A'的数量大于1,则挂科
    2. 如果字符不为‘A’,则判断是否为'L',如果是'L',则判断前后是否为'L',是则说明已经挂科

    代码

    checkRecord.go

    package _551_Student_Attendance_Record_I
    
    func CheckRecord(s string) bool {
        sRune := []rune(s)
        len1 := len(sRune)
    
        var absentNum int
        for i := 0; i < len1; i++ {
            if sRune[i] == rune('A') {
                absentNum++
    
                if absentNum >=2 {
                    return false
                }
            } else if rune('L') == sRune[i] && i > 0 && i < len1 - 1 && rune('L') == sRune[i-1] && rune('L') == sRune[i+1] {
                return false
            }
        }
    
        return true
    }
    
    

    测试

    checkRecord_test.go

    package _551_Student_Attendance_Record_I
    
    import "testing"
    
    func TestCheckRecord(t *testing.T) {
        var tests = []struct{
            input string
            output bool
        } {
            {"PPALLL", false},
        }
    
        for _, v := range tests {
            ret := CheckRecord(v.input)
    
            if ret == v.output {
                t.Logf("pass")
            } else {
                t.Errorf("fail, want %+v, get %+v\n", v.output, ret)
            }
        }
    }
    
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 58]551. Student

        本文链接:https://www.haomeiwen.com/subject/zroudxtx.html