題目描述:
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.
這道題目十分簡(jiǎn)單,最直觀的解法就是對(duì)A和L的次數(shù)記錄下來(lái),然后要是超出就返回false。但是我采取的解法是使用向量機(jī)(向量機(jī)在處理字符串問(wèn)題上十分好用
)
bool checkRecord(string s) {
vector<vector<int>> vm= {
{0,1,3}, //當(dāng)前位置的前一個(gè)位置不為L(zhǎng),且沒(méi)有A的狀態(tài)
{0,2,3}, // 當(dāng)前位置的前一個(gè)位置時(shí)L,且沒(méi)有A的狀態(tài)
{0,-1,3}, // 當(dāng)前位置的前兩個(gè)位置都是L,且沒(méi)有A的狀態(tài)
{3,4,-1}, // 當(dāng)前位置的前一個(gè)位置不為L(zhǎng),且有一個(gè)A的狀態(tài)
{3,5,-1}, // 當(dāng)前位置的前一個(gè)位置為L(zhǎng),且有一個(gè)A的狀態(tài)
{3,-1,-1} // 當(dāng)前位置的前兩個(gè)位置為L(zhǎng),且有一個(gè)A的狀態(tài)
};
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;
}