From bb7f9375daaad6899e7158054bc7f5bfc1704dc7 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Wed, 1 Jan 2020 19:40:52 +0800 Subject: [PATCH] Create 393. UTF-8 Validation.md --- solutions/393. UTF-8 Validation.md | 42 ++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 solutions/393. UTF-8 Validation.md diff --git a/solutions/393. UTF-8 Validation.md b/solutions/393. UTF-8 Validation.md new file mode 100644 index 0000000..4518bf8 --- /dev/null +++ b/solutions/393. UTF-8 Validation.md @@ -0,0 +1,42 @@ +# [393. UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) +# 思路 + +此题让我们验证给定的编码是否是合法的 UTF-8 编码。 + +此题感觉没啥好说的,按照题目进行验证即可,详见代码。 + +**需要注意的是题目给的是【单个字符】的UTF-8规则,而实际却让我们判断的是【字符序列】** 估计这也是为什么那么多人给此题倒赞吧....实属坑题 + +# C++ +``` C++ +class Solution { +private: + int pre_1(int n){ // 计算有多少个前导1 + int mask = 128; + int res = 0; + while(mask & n){ + res++; + mask >>= 1; + } + return res; + } +public: + bool validUtf8(vector& data) { + int i = 0; + # define start_with_10(n) ((n & 0x000000c0) == 128) + while(i < data.size()){ + int num_pre1 = pre_1(data[i]); + if(!num_pre1) i++; + else{ + if(num_pre1 == 1 || num_pre1 > 4) return false; + for(int j = 1; j < num_pre1; j++){ + if(j + i == data.size() || !start_with_10(data[j+i])) + return false; + } + i += num_pre1; + } + } + return true; + } +}; +```