LeetCode 271. Encode and Decode Strings

本文介绍了一种字符串编码和解码的方法。编码通过在每个字符串前添加长度和特殊符号来实现,便于后续的解码过程。解码则依据这些特殊符号及长度信息将编码后的字符串还原为原始形式。示例代码展示了如何对一组字符串进行编码和解码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is to encode the string not to COMPRESS the string.

This is one possible answer.

#include <string>
#include <vector>
#include <iostream>
using namespace std;

string encode(vector<string>& strs) {
  string res = "";
  for(int i = 0; i < strs.size(); ++i) {
    res += to_string(strs[i].size()) + "#" + strs[i];
  }
  return res;
}

vector<string> decode(string s) {
  vector<string> res;
  int i = 0, j = 0;
  while(i < s.size()) {
    if(s[i] != '#') {i++; continue;}
    else {
      int len = stoi(s.substr(j, i - j));
      res.push_back(s.substr(i + 1, len));
      i = i + 1 + len;
      j = i;
    }
  }
  //while(s.size() > 0) {
  //  int pos = s.find_first_of('#');   // if not know this function, better to use two pointers.
  //  int len = stoi(s.substr(0, pos));
  //  res.push_back(s.substr(pos + 1, len));
  //  s = s.substr(pos + len + 1);
  //}
  return res;
}

int main(void) {
  vector<string> words{"tammy", "is", "a", "good", "girl"};
  string s = encode(words);
  cout << endl;
  vector<string> res = decode(s);
  for(int i = 0; i < res.size(); ++i) cout << res[i] << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值