优化前:
c++
bool checkRecord(string s) {
int logA = 0;
for (int i=0; i<s.length(); i++) {
if (s[i]=='A') {
logA++;
if (logA>1) {
return 0;
}
}
if (i>1&&s[i]=='L'&&s[i-1]=='L'&&s[i-2]=='L') {
return 0;
}
}
return 1;
}
优化后:
class Solution {
public:
bool checkRecord(string s) {
int count_A = 0;
int pos = 0;
while(pos<s.length())
{
if(s[pos]=='A')
{
count_A++;
pos++;
if(count_A>1)
return false;
}
else if(s[pos]=='L')
{
int count = 0;
while(pos<s.length()&&s[pos]=='L')
{
count++;
pos++;
}
if(count>2)
return false;
}
else
pos++;
}
return true;
}
};