My Java Solution, Straight-forward


  • 0
    S
    public class Solution {
        public boolean validUtf8(int[] data) {
            int n = data.length;
            int i = 0;
            while (i < n) {
                int d = data[i];
                // case1
                if (0 <= d && d <= 127) i++;
                // case2
                else if (192 <= d && d <= 223 && i + 1 < n && check(data[i + 1])) i += 2;
                // case 3
                else if (224 <= d && d <= 239 && i + 2 < n && check(data[i + 1]) && check(data[i + 2])) i += 3;
                // case 4
                else if (240 <= d && d <= 247 && i + 3 < n && check(data[i + 1]) && check(data[i + 2]) && check(data[i + 3])) i += 4;
                else return false;
            }
            return true;
        }
        
        public boolean check(int d) {
            return 128 <= d && d <= 191;
        }
    }
    

Log in to reply
 

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