From 6ce47d87ef8d6ce4ba07bb238e7f8683baf3bf17 Mon Sep 17 00:00:00 2001 From: ktony Date: Tue, 20 Aug 2024 00:05:54 -0400 Subject: [PATCH] 659. Encode and Decode Strings modify --- encode-and-decode-strings/TonyKim9401.java | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/encode-and-decode-strings/TonyKim9401.java b/encode-and-decode-strings/TonyKim9401.java index 4d0d0073e..93d16d4de 100644 --- a/encode-and-decode-strings/TonyKim9401.java +++ b/encode-and-decode-strings/TonyKim9401.java @@ -1,16 +1,15 @@ public class Solution { - // time complexity: O(n) - // space complexity: O(n) - Map encode = new HashMap<>(); /* * @param strs: a list of strings * @return: encodes a list of strings to a single string. */ public String encode(List strs) { // write your code here - int key = 0; - for (String str : strs) encode.put(key++, str); - return String.valueOf(key); + StringBuilder sb = new StringBuilder(); + for (String str : strs) { + sb.append(str.length()).append("#").append(str); + } + return sb.toString(); } /* @@ -20,8 +19,14 @@ public String encode(List strs) { public List decode(String str) { // write your code here List output = new ArrayList<>(); - int decode = 0; - while (decode < Integer.valueOf(str)) output.add(encode.get(decode++)); + int i = 0; + while (i < str.length()) { + int idx = str.indexOf('#', i); + int length = Integer.parseInt(str.substring(i, idx)); + String s = str.substring(idx + 1, idx + 1 + length); + output.add(s); + i = idx + 1 + length; + } return output; } }