Blind 75
Encode and Decode Strings
- Problem
- LC 271
- Category
- String
- File
- blind75_LC271EncodeAndDecodeStrings.java
- Path
- pkg5leetcode/blind75/blind75_LC271EncodeAndDecodeStrings.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC271EncodeAndDecodeStrings.java
- Approach
- Length-prefix encoding: len#payload for each string.
- Complexity
- Time O(total chars), Space O(total chars)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Encode and Decode Strings | LC 2715 * APPROACH: Length-prefix encoding: len#payload for each string.6 * COMPLEXITY: Time O(total chars), Space O(total chars)7 */8import java.util.*;9 10public class blind75_LC271EncodeAndDecodeStrings {11 static String encode(List<String> strs) {12 StringBuilder sb = new StringBuilder();13 for (String s : strs) sb.append(s.length()).append('#').append(s);14 return sb.toString();15 }16 17 static List<String> decode(String s) {18 List<String> res = new ArrayList<>();19 int i = 0;20 while (i < s.length()) {21 int j = s.indexOf('#', i);22 int len = Integer.parseInt(s.substring(i, j));23 i = j + 1;24 res.add(s.substring(i, i + len));25 i += len;26 }27 return res;28 }29 30 public static void main(String[] args) {31 List<String> in = Arrays.asList("hello", "world", "leet#code");32 List<String> out = decode(encode(in));33 check(out.equals(in), "case1");34 List<String> empty = Arrays.asList("");35 check(decode(encode(empty)).equals(empty), "case2");36 System.out.println("all tests passed");37 }38 39 static void check(boolean cond, String name) {40 if (!cond) throw new AssertionError("FAILED: " + name);41 System.out.println(" PASS " + name);42 }43}