File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public String encode (List <String > strs ) {
3
+ StringBuilder res = new StringBuilder ();
4
+ for (String s : strs ) {
5
+ res .append (s .length ()).append ('|' ).append (s );
6
+ }
7
+ return res .toString ();
8
+ }
9
+
10
+
11
+ /*
12
+ * number + | + string
13
+ * read number until |
14
+ * move pointer, read substring
15
+ *
16
+ * tc : O(n) when n is the length of encoded string
17
+ * sc : O(1)
18
+ * */
19
+ public List <String > decode (String str ) {
20
+ List <String > res = new ArrayList <>();
21
+ int start = 0 ;
22
+ while (start < str .length ()) {
23
+ int cur = start ;
24
+ //read until |
25
+ while (str .charAt (cur ) != '|' ) {
26
+ cur ++;
27
+ }
28
+ int length = Integer .parseInt (str .substring (start , cur ));
29
+ start = cur + 1 ;
30
+ cur = start + length ;
31
+ res .add (str .substring (start , cur ));
32
+ start = cur ;
33
+ }
34
+ return res ;
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments