File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+ public boolean validUtf8 (int [] data ) {
3
+ ArrayList <String > octs = new ArrayList <>();
4
+
5
+ for (int i : data ) {
6
+ octs .add (Integer .toBinaryString ( (1 << 8 ) | i ).substring ( 1 ));
7
+ }
8
+
9
+ int cIndex = 0 ;
10
+
11
+ while (cIndex < data .length ) {
12
+ String b = octs .get (cIndex );
13
+
14
+ if (b .substring (0 , 5 ).equals ("11110" )) { // check 4-byte
15
+ if (cIndex + 3 >= octs .size ()
16
+ || !octs .get (cIndex +1 ).substring (0 , 2 ).equals ("10" )
17
+ || !octs .get (cIndex +2 ).substring (0 , 2 ).equals ("10" )
18
+ || !octs .get (cIndex +3 ).substring (0 , 2 ).equals ("10" )) {
19
+ return false ;
20
+ }
21
+
22
+ cIndex += 4 ;
23
+ } else if (b .substring (0 , 4 ).equals ("1110" )) { // check 3-byte
24
+
25
+ if (cIndex + 2 >= octs .size ()
26
+ || !octs .get (cIndex +1 ).substring (0 , 2 ).equals ("10" )
27
+ || !octs .get (cIndex +2 ).substring (0 , 2 ).equals ("10" )) {
28
+ return false ;
29
+ }
30
+
31
+ cIndex += 3 ;
32
+ } else if (b .substring (0 , 3 ).equals ("110" )) { // check 2-byte
33
+ if (cIndex + 1 >= octs .size ()
34
+ || !octs .get (cIndex +1 ).substring (0 , 2 ).equals ("10" )) {
35
+ return false ;
36
+ }
37
+
38
+ cIndex += 2 ;
39
+ } else if (b .substring (0 , 1 ).equals ("0" )) { // check 1-byte
40
+ cIndex += 1 ;
41
+ } else {
42
+ return false ;
43
+ }
44
+ }
45
+
46
+ return true ;
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments