[LeetCode By Go 58]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

解题思路

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

    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/54e479d64432
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞