C++ 中的 UTF-8 驗證


假設我們有一個整數列表表示資料。我們需要檢查它是否為有效的 UTF-8 編碼。一個 UTF-8 字元可以是 1 到 4 個位元組長。有一些屬性:

  • 對於 1 位元組字元,第一個位元位為 0,後面跟著它的 Unicode 碼。

  • 對於 n 位元組字元,前 n 個位元位都為 1,第 n+1 個位元位為 0,後面跟著 n-1 個位元組,其最高兩位為 10。

所以編碼技術如下:

字元數值範圍UTF-8 位元組序列
0000 0000 0000 007F0xxxxxxx
0000 0080 0000 07FF110xxxxx 10xxxxxx
0000 0800 0000 FFFF1110xxxx 10xxxxxx 10xxxxxx
0001 0000 0010 FFFF11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

所以如果輸入類似於 [197, 130, 1],它表示位元組序列 11000101 10000010 00000001,因此這將返回 true。它是一個有效的 utf-8 編碼,表示一個 2 位元組字元後跟一個 1 位元組字元。

為了解決這個問題,我們將遵循以下步驟:

  • cnt := 0

  • for i in range 0 to size of data array

    • x := data[i]

    • if cnt is 0, then

      • if x/32 = 110, then set cnt as 1

      • otherwise when x/16 = 1110, then cnt = 2

      • otherwise when x/8 = 11110, then cnt = 3

      • otherwise when x/128 is 0, then return false

    • otherwise when x /64 is not 10, then return false and decrease cnt by 1

  • return true when cnt is 0

示例(C++)

讓我們看看以下實現以獲得更好的理解:

 即時演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool validUtf8(vector<int>& data) {
      int cnt = 0;
      for(int i = 0; i <data.size(); i++){
         int x = data[i];
         if(!cnt){
            if((x >> 5) == 0b110){
               cnt = 1;
            }
            else if((x >> 4) == 0b1110){
               cnt = 2;
            }
            else if((x >> 3) == 0b11110){
               cnt = 3;
            }
            else if((x >> 7) != 0) return false;
            } else {
               if((x >> 6) != 0b10) return false;
               cnt--;
            }
         }
         return cnt == 0;
      }
};
main(){
   Solution ob;
   vector<int> v = {197,130,1};
   cout << (ob.validUtf8(v));
}

輸入

[197,130,1]

輸出

1

更新於: 2020年5月2日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告