Skip to content

Commit

Permalink
659. Encode and Decode Strings modify
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyKim9401 committed Aug 24, 2024
1 parent 33f0817 commit c1f9078
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions encode-and-decode-strings/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
public class Solution {
// time complexity: O(n)
// space complexity: O(n)
Map<Integer, String> encode = new HashMap<>();
// Time complexity: O(n)
// Space complexity: O(n)
/*
* @param strs: a list of strings
* @return: encodes a list of strings to a single string.
*/
public String encode(List<String> 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();
}

/*
Expand All @@ -20,8 +21,14 @@ public String encode(List<String> strs) {
public List<String> decode(String str) {
// write your code here
List<String> 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;
}
}

0 comments on commit c1f9078

Please sign in to comment.