C++ 中的字串編碼和解碼


假設我們有一組字串。我們需要設計一個演算法,將這組字串編碼成一個字串。我們還需要設計一個解碼器,將編碼後的字串解碼回原始的字串列表。假設我們在這些機器上安裝了編碼器和解碼器,並且有兩個不同的函式,如下所示:

機器 1(傳送方)具有以下函式

string encode(vector<string< strs) {
   //code to read strings and return encoded_string;
}

機器 2(接收方)具有以下函式

vector<string< decode(string s) {
   //code to decode encoded_string and returns strs;
}

因此,如果輸入類似於 {"hello", "world", "coding", "challenge"},則輸出將是編碼字串 5#hello5#world6#coding9#challenge,解碼形式為 [hello, world, coding, challenge, ]

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

  • 定義一個函式 encode(),它將接收一個字串陣列 strs,

  • ret := 空字串

  • 初始化 i := 0,當 i < strs 的大小,更新(i 加 1),執行以下操作:

    • ret := ret 連線 strs[i] 的大小

  • 返回 ret

  • 定義一個函式 getNext(),它將接收 x、start、s,

  • idx := s 的大小

  • 初始化 i := start,當 i < s 的大小,更新(i 加 1),執行以下操作:

    • 如果 s[i] 與 x 相同,則:

      • idx := i

      • 退出迴圈

  • 返回 idx

  • 定義方法 decode,它將接收 s

  • 定義一個數組 ret

  • i := 0

  • n := s 的大小

  • 當 i < n 時,執行以下操作:

    • hashPos := getNext('#', i, s)

    • len := (從索引 (i 到 hashPos - i - 1) 擷取 s 的子字串作為整數

    • i := hashPos + 1

    • 將從索引 (i 到 len - 1) 擷取 s 的子字串插入到 ret 的末尾

    • i := i + len

  • 返回 ret

示例

讓我們看看下面的實現,以便更好地理解:

線上演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Codec {
public:
   string encode(vector<string>& strs) {
      string ret = "";
      for (int i = 0; i < strs.size(); i++) {
         ret += to_string(strs[i].size()) + "#" + strs[i];
      }
      return ret;
   }
   int getNext(char x, int start, string s){
      int idx = s.size();
      for (int i = start; i < s.size(); i++) {
         if (s[i] == x) {
            idx = i;
            break;
         }
      }
      return idx;
   }
   vector<string> decode(string s) {
      vector<string> ret;
      int i = 0;
      int n = s.size();
      while (i < n) {
         int hashPos = getNext('#', i, s);
         int len = stoi(s.substr(i, hashPos - i));
         i = hashPos + 1;
         ret.push_back(s.substr(i, len));
         i += len;
      }
      return ret;
   }
};
main(){
   Codec ob;
   vector<string> v = {"hello", "world", "coding", "challenge"};
   string enc = (ob.encode(v));
   cout << "Encoded String " << enc << endl;
   print_vector(ob.decode(enc));
}

輸入

{"hello", "world", "coding", "challenge"}

輸出

Encoded String 5#hello5#world6#coding9#challenge
[hello, world, coding, challenge, ]

更新時間: 2020-11-18

4K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告