博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Encode and Decode Strings
阅读量:6445 次
发布时间:2019-06-23

本文共 1732 字,大约阅读时间需要 5 分钟。

Problem

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Machine 1 (sender) has the function:

string encode(vector
strs) { // ... your code return encoded_string;}

Machine 2 (receiver) has the function:

vector
decode(string s) { //... your code return strs;}

So Machine 1 does:

string encoded_string = encode(strs);

and Machine 2 does:

vector
strs2 = decode(encoded_string);

strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods.

Note

The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.

Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.

Solution

public class Codec {    // Encodes a list of strings to a single string.    public String encode(List
strs) { StringBuilder sb = new StringBuilder(); for (String str: strs) { sb.append(str + "\n"); } return sb.toString(); } // Decodes a single string to a list of strings. public List
decode(String s) { List
strs = new ArrayList<>(); int pre = 0, i = 0; while (i < s.length()) { if (s.charAt(i) == '\n') { strs.add(s.substring(pre, i)); pre = i+1; i = i+1; } else i++; } return strs; }}

转载地址:http://duvwo.baihongyu.com/

你可能感兴趣的文章
理解Docker :Docker 网络
查看>>
java int和String类型之间的相互转换
查看>>
通过Application存取公共数据比如登录信息等..
查看>>
U盘中毒了?教你如何删除System Volume Information这个顽固文件夹
查看>>
intellij maven配置与使用
查看>>
CentOS安装ntfs-3g
查看>>
SpringMVC文件下载与JSON格式
查看>>
postgre查询表和记录数
查看>>
Q:图像太大,在opencv上显示不完全
查看>>
ubuntu -redis
查看>>
[转]c++ 结构体和类的区别
查看>>
修正锚点跳转位置 避免头部fixed固定部分遮挡
查看>>
Dubbo序列化多个CopyOnWriteArrayList对象变成同一对象的一个大坑!!
查看>>
linux下ping不通的解决方法
查看>>
关于大型网站技术演进的思考(三)---- 存储的瓶颈(3)
查看>>
利用ItextPdf、core-renderer-R8 来生成PDF
查看>>
irc操作小记
查看>>
JAVA 与 PHP 的不同和相同
查看>>
03-Java环境变量配置
查看>>
Python mysql操作
查看>>