Question

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<string> strs) {
// ... your code
return encoded_string;
}

Machine 2 (receiver) has the function:

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

So Machine 1 does:

string encoded_string = encode(strs);

and Machine 2 does:

vector<string> 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 1 -- JSON format

第一种方法是参考的JSON的规则。

Encode: 我们将输入的字符串数组封装成JSON中的array。[ (left bracket) and ] (right bracket) 表示开头的结尾。中间的分隔用, (comma)。然后对于每个字符串,是 wrapped in double quotes。

由于字符串中本来就可能有双引号或是back slash (\),所以我们需要对这两种符号做转义。方法是多加一个back slash

如 原字符串 \"aafg"  -> \\\"aafg\"

JSON里还有更复杂的字符串处理方法。但我们这里的目标只是让encode,再decode后的字符串相同,所以不必那么复杂。

Decode处理原则如下

1. 一个boolean的variable记录当前应该是下一个字符串的开头还是当前字符串的结束

2. 碰到bracket,根据是开始/结束,新建一个空字符串/将当前的字符串存入结果中

3. 碰到back slash,看它下一个元素是否是back slash / bracket,如果是,则将它下一个元素加到字符串中,计数加一。

 public class Codec {
private final char start = '[';
private final char end = ']';
private final char include = '"';
private final char strSplit = ','; // Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
sb.append(start);
for (String str : strs) {
sb.append(include);
int len = str.length();
for (int i = 0; i < len; i++) {
char current = str.charAt(i);
if (current == '"' || current == '\\') {
sb.append('\\');
}
sb.append(current);
}
sb.append(include);
sb.append(strSplit);
}
sb.append(end);
return sb.toString();
} // Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> result = new ArrayList<String>();
if (s == null || s.length() < 1) {
return result;
}
int len = s.length();
if (s.charAt(0) != start || s.charAt(len - 1) != end) {
return result;
}
boolean startSymbol = true;
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len - 1; i++) {
char current = s.charAt(i);
if (current == include) {
if (startSymbol) {
sb = new StringBuilder();
} else {
result.add(sb.toString());
}
startSymbol = !startSymbol;
continue;
}
if (current == strSplit && startSymbol) {
continue;
}
if (current == '\\') {
char next = s.charAt(i + 1);
if (next == '\\' || next == '"') {
sb.append(next);
i++;
continue;
}
}
sb.append(current);
}
return result;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));

Solution 2

利用了Java里String的 int indexOf(int ch, int fromIndex)函数。

同时存入字符串和字符串的长度。

 public class Codec {

     // Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String str : strs) {
sb.append(str.length()).append('/').append(str);
}
return sb.toString();
} // Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> result = new ArrayList<String>();
int length = s.length();
int i = 0;
while (i < length) {
int slash = s.indexOf('/', i);
int size = Integer.valueOf(s.substring(i, slash));
result.add(s.substring(slash + 1, slash + size + 1));
i = slash + size + 1;
}
return result;
}
}

Encode and Decode Strings 解答的更多相关文章

  1. [LeetCode] Encode and Decode Strings 加码解码字符串

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  2. LeetCode Encode and Decode Strings

    原题链接在这里:https://leetcode.com/problems/encode-and-decode-strings/ 题目: Design an algorithm to encode a ...

  3. Encode and Decode Strings

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  4. 271. Encode and Decode Strings

    题目: Design an algorithm to encode a list of strings to a string. The encoded string is then sent ove ...

  5. [LeetCode#271] Encode and Decode Strings

    Problem: Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...

  6. [Swift]LeetCode271. 加码解码字符串 $ Encode and Decode Strings

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  7. Encode and Decode Strings -- LeetCode

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  8. [LeetCode] 271. Encode and Decode Strings 加码解码字符串

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  9. [LC] 271. Encode and Decode Strings

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

随机推荐

  1. javascript 典型闭包的用法

    <body><input type="radio" id="radio1" name="readionGroup" /&g ...

  2. Adroid APPIUM实例步骤

      1.下载eclipse 2.安装java 配置环境变量 3.eclipse 安装adt android development tools 4.android sdk manager 安装tool ...

  3. Django之Cookie与Session

    一.cookie 1.cookie使用 def cookie(request): print(request.COOKIES) # 获取所有的COOKIES obj = render(request, ...

  4. Android Studio新手全然指引

    Android Studio新手全然指引 @author ASCE1885的 Github 简书 微博 CSDN Android Studio的下载及安装 假设你的电脑能够FQ,那么请直接到Andro ...

  5. mount USB Device(U disk) on crux based on vmware

    1. 在 /mnt 下建立一个名叫USB的文件夹,文件夹名自定 cd /mnt mkdir USB 2. 查看一下磁盘分区情况 fdisk –l 3. 插入U盘 4. 再次查看磁盘分区情况,对比第一次 ...

  6. Linux系统相关

    1. 图形界面启动的是哪个运行级别? 而我们平时用的命令行模式又是哪个运行级别? 除了图形和命令行模式两个常用级别外,其他运行级别代表什么涵义?如何更改系统的运行级别?图形界面启动的是5级别,命令行模 ...

  7. Linux基础知识(二)

    1. 请回答,32位和64位有什么区别呢?什么时候安装32位的,又什么时候安装64位操作系统呢?如何查看系统是32位的还是64位的? 所谓的32位.64位指的是CPU的GPRs(General-Pur ...

  8. c#利用VM_COPYDATA实现进程间通信

    c#进程间的通信方式很多种,只会这种,感觉比较简单.不懂原理,能用就行. 假设有两个程序:server(主进程),client(子进程) 1.server端: /*定义一个结构体,用来接收从子进程传过 ...

  9. javascript什么是函数

    函数是完成某个特定功能的一组词语.如没有函数,完成任务可能需要五行.十行.甚至更多的代码. 这是未满就可以把完成特定功能的代码块放到一个函数里,直接调用这个函数,就省重复输入大量代码的麻烦. 如何定义 ...

  10. 先装Net Framework 后 装 IIS的处理办法

    先装IIS话,后面装Net Framework时候会自动注册 处理aspx和ashx等的处理扩展程序 先装Net Framework 后 装 IIS.扩展程序注册在命令:aspnet_regiis - ...