LeetCode 271: Encode and Decode String

LeetCode 271: Encode and Decode String

 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.

Implement the encode and decode methods.

You are not allowed to solve the problem using any serialize methods (such as eval).


Example 1:

Input: dummy_input = ["Hello","World"]
Output: ["Hello","World"]
Explanation:
Machine 1:
Codec encoder = new Codec();
String msg = encoder.encode(strs);
Machine 1 ---msg---> Machine 2

Machine 2:
Codec decoder = new Codec();
String[] strs = decoder.decode(msg);

Example 2:

Input: dummy_input = [""]
Output: [""]



Solution:
Decided to use  => len(str) + "#" + str   as encoding

public class Codec {

public String encode(List<String> strs) {
String ans = "";
for (int i = 0; i < strs.size(); i++) {
String k = strs.get(i);
int len = k.length();
ans += String.valueOf(len) + "#" + k;
}
return ans;
}

public List<String> decode(String str) {
List<String> ans = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
int num = 0;
while (str.charAt(i) == '0' || str.charAt(i) == '1' || str.charAt(i) == '2' || str.charAt(i) == '3' || str.charAt(i) == '4' || str.charAt(i) == '5' || str.charAt(i) == '6' || str.charAt(i) == '7' || str.charAt(i) == '8' || str.charAt(i) == '9') {
num = num * 10 + (str.charAt(i) - '0');
i++;
if (str.charAt(i) == '#') {
i++;
break;
}
}

String temp = "";
while(num > 0 && i < str.length()){
temp += str.charAt(i);
i++;
num--;
}
i--;
ans.add(temp);
}
return ans;
}
}

Comments

Popular posts from this blog

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.