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:

'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.

这道题目十分简单,最直观的解法就是对A和L的次数记录下来,然后要是超出就返回false。但是我采取的解法是使用向量机(向量机在处理字符串问题上十分好用

bool checkRecord(string s) {
        vector> vm= {
            {0,1,3},    //当前位置的前一个位置不为L,且没有A的状态
            {0,2,3},    // 当前位置的前一个位置时L,且没有A的状态
            {0,-1,3},   // 当前位置的前两个位置都是L,且没有A的状态
            {3,4,-1},   // 当前位置的前一个位置不为L,且有一个A的状态
            {3,5,-1},   // 当前位置的前一个位置为L,且有一个A的状态
            {3,-1,-1}   // 当前位置的前两个位置为L,且有一个A的状态
        };
        int currentState = 0;
        for(int i = 0;i < s.size();i++){
            if(s[i] == 'P'){
                currentState = vm[currentState][0];
            }else if(s[i] == 'L'){
                currentState = vm[currentState][1];
            }else if(s[i] == 'A'){
                currentState = vm[currentState][2];
            }
            if(currentState == -1){
                return false;
            }
        }
        return true;
    }

你可能感兴趣的:(Leetcode 551. Student Attendance Record I)