File tree Expand file tree Collapse file tree
encode-and-decode-strings Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ public class Solution {
2+ /*
3+ * @param strs: a list of strings
4+ * @return: encodes a list of strings to a single string.
5+ */
6+ public String encode (List <String > strs ) {
7+ StringBuilder sb = new StringBuilder ();
8+ for (String s : strs ) {
9+ sb .append (s .length ());
10+ sb .append ('#' );
11+ sb .append (s );
12+ }
13+ return sb .toString ();
14+ }
15+
16+ /*
17+ * @param str: A string
18+ * @return: decodes a single string to a list of strings
19+ */
20+ public List <String > decode (String str ) {
21+ List <String > res = new ArrayList <>();
22+ int i = 0 ;
23+ while (i < str .length ()) {
24+ // '#' 앞의 숫자를 길이로 파싱
25+ int len = 0 ;
26+ while (str .charAt (i ) != '#' ) {
27+ len = len * 10 + (str .charAt (i ) - '0' );
28+ i ++;
29+ }
30+ i ++; // '#' 건너뛰기
31+
32+ // 정확히 len 글자만 잘라내기
33+ res .add (str .substring (i , i + len ));
34+ i += len ;
35+ }
36+ return res ;
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments