题目
You are given a string representing an attendance record for a student. The record only contains the following three characters:
- 'A' : Absent.
- 'L' : Late.
- '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
解题思路
- 循环遍历字符串,判断字符是否为'A',如果是,则累计'A'的数量,如果‘A'的数量大于1,则挂科
- 如果字符不为‘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)
}
}
}
网友评论