mediumArrays & Hashing

Encode and Decode Strings

Encode a list of strings into one string, then decode it back without losing empty strings or punctuation. Use length#text for each entry, concatenated together.

Work through the cases

3 examples

Input notation

The number of strings on line 1, followed by that many lines. Empty lines represent empty strings.

Expected result

The encoded string on the first line, followed by each decoded string on its own line.
Case 1

Input

2
hi
a#b

Expected output

2#hi3#a#b
hi
a#b
Case 2

Input

2

x

Expected output

0#1#x

x
Case 3

Input

1
#

Expected output

1##
#

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

Store each string as its length, a # separator, and the text. Decode by reading a length and consuming exactly that many characters. Empty strings and # inside text are unambiguous. Time and space: O(total characters). These methods demonstrate the codec; print the encoded result and decoded lines to match the examples.

import java.util.*;
class Codec {
    String encode(List<String> words) { StringBuilder b=new StringBuilder(); for(String w:words)b.append(w.length()).append("#").append(w); return b.toString(); }
    List<String> decode(String text) { List<String> out=new ArrayList<>(); int i=0; while(i<text.length()){int end=text.indexOf("#",i);int length=Integer.parseInt(text.substring(i,end));i=end+1;out.add(text.substring(i,i+length));i+=length;}return out;}
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.