From 5160187cc6a1b6a9f8ae2ce508fd106e6f103e48 Mon Sep 17 00:00:00 2001 From: openset Date: Sun, 22 Sep 2019 12:23:08 +0800 Subject: [PATCH] Add: UTF-8 Validation --- internal/leetcode/problems_status.go | 2 + problems/utf-8-validation/utf_8_validation.go | 22 +++++++++- .../utf-8-validation/utf_8_validation_test.go | 40 ++++++++++++++++++- 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/internal/leetcode/problems_status.go b/internal/leetcode/problems_status.go index 4a2271d5f..6f8c2fe59 100644 --- a/internal/leetcode/problems_status.go +++ b/internal/leetcode/problems_status.go @@ -37,6 +37,7 @@ var problemStatus = map[int]bool{ 50: true, 53: true, 58: true, + 65: true, 66: true, 67: true, 69: true, @@ -97,6 +98,7 @@ var problemStatus = map[int]bool{ 371: true, 383: true, 387: true, + 393: true, 412: true, 413: true, 414: true, diff --git a/problems/utf-8-validation/utf_8_validation.go b/problems/utf-8-validation/utf_8_validation.go index 4a943d252..f6c48253b 100644 --- a/problems/utf-8-validation/utf_8_validation.go +++ b/problems/utf-8-validation/utf_8_validation.go @@ -1 +1,21 @@ -package utf_8_validation +package problem_393 + +func validUtf8(data []int) bool { + u := 0 + for _, v := range data { + if u == 0 && v>>7 == 0 { // 0b0 + u = 0 + } else if u == 0 && v>>5 == 6 { // 0b110 + u = 1 + } else if u == 0 && v>>4 == 14 { // 0b1110 + u = 2 + } else if u == 0 && v>>3 == 30 { // 0b11110 + u = 3 + } else if u > 0 && v>>6 == 2 { // 0b10 + u-- + } else { + return false + } + } + return u == 0 +} diff --git a/problems/utf-8-validation/utf_8_validation_test.go b/problems/utf-8-validation/utf_8_validation_test.go index 4a943d252..cd350f7d6 100644 --- a/problems/utf-8-validation/utf_8_validation_test.go +++ b/problems/utf-8-validation/utf_8_validation_test.go @@ -1 +1,39 @@ -package utf_8_validation +package problem_393 + +import "testing" + +type caseType struct { + input []int + expected bool +} + +func TestValidUtf8(t *testing.T) { + tests := [...]caseType{ + { + input: []int{197}, + expected: false, + }, + { + input: []int{197, 130, 1}, + expected: true, + }, + { + input: []int{235, 140, 4}, + expected: false, + }, + { + input: []int{248}, + expected: false, + }, + { + input: []int{194, 155, 231, 184, 185, 246, 176, 131, 161, 222, 174, 227, 162, 134, 241, 154, 168, 185, 218, 178, 229, 187, 139, 246, 178, 187, 139, 204, 146, 225, 148, 179, 245, 139, 172, 134, 193, 156, 233, 131, 154, 240, 166, 188, 190, 216, 150, 230, 145, 144, 240, 167, 140, 163, 221, 190, 238, 168, 139, 241, 154, 159, 164, 199, 170, 224, 173, 140, 244, 182, 143, 134, 206, 181, 227, 172, 141, 241, 146, 159, 170, 202, 134, 230, 142, 163, 244, 172, 140, 191}, + expected: true, + }, + } + for _, tc := range tests { + output := validUtf8(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}