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, ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP