State machine with bit encoding in Java


  • 0
    Y
    public class Solution {
        public boolean checkRecord(String s) {
            int state = 0b000;  // the least significant two bits are used to encode # of continuous L(s),
                                // the thrid least significant bit is used to encode # of A(s).
            
            for (char ch : s.toCharArray()) {
                switch (ch) {
                    case 'P':
                        state &= 0b100;
                        break;
                        
                    case 'A':
                        if ((state & 0b100) > 0) {
                            return false;
                        } else {
                            state = 0b100;
                        }
                        break;
                        
                    case 'L':
                        if ((state & 0b011) >= 2) {
                            return false;
                        } else {
                            state += 1;
                        }
                        break;
                }
    
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.