สมมติว่าเรามีรายการสตริง เราต้องออกแบบอัลกอริทึมที่สามารถเข้ารหัสรายการสตริงให้เป็นสตริงได้ นอกจากนี้เรายังต้องสร้างตัวถอดรหัสที่จะถอดรหัสกลับไปยังรายการสตริงเดิม สมมติว่าเรามีตัวเข้ารหัสและตัวถอดรหัสติดตั้งอยู่ในเครื่องเหล่านี้ และมีฟังก์ชันที่แตกต่างกันสองแบบดังนี้ -
เครื่อง 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"} ผลลัพธ์ที่ได้จะเป็น Encoded String 5#hello5#world6#coding9#challenge รูปแบบถอดรหัส [hello, world, coding , ท้าทาย, ]
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
-
กำหนดฟังก์ชัน encode() ซึ่งจะใช้อาร์เรย์ strs
-
ret :=สตริงว่าง
-
สำหรับการเริ่มต้น i :=0 เมื่อฉัน <ขนาดของ strs ให้อัปเดต (เพิ่ม i ขึ้น 1) ทำ -
-
ret :=ret เชื่อมขนาดของ strs[i]
-
-
รีเทิร์น
-
กำหนดฟังก์ชัน getNext() ซึ่งจะใช้เวลา x, start, s,
-
idx :=ขนาดของ s
-
สำหรับ initialize i :=start, when i
-
ถ้า s[i] เหมือนกับ x แล้ว −
-
idx :=ผม
-
ออกจากวง
-
-
-
ส่งคืน idx
-
กำหนดวิธีการถอดรหัสนี้จะใช้เวลา s
-
กำหนดอาร์เรย์ ret
-
ผม :=0
-
n :=ขนาดของ s
-
ในขณะที่ฉัน
-
hashPos :=getNext('#', i, s)
-
len :=(สตริงย่อยของ s จากดัชนี (i ถึง hashPos - i - 1) เป็นจำนวนเต็ม
-
ผม :=hashPos + 1
-
แทรกสตริงย่อยของ s จากดัชนี (i ถึง len - 1) ที่ส่วนท้ายของ 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, ]