File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .ArrayList ;
2
+ import java .util .List ;
3
+ // n: 문자열 리스트 길이, m: 각 문자열의 길이.
4
+
5
+ // 시간 복잡도
6
+ // Encoding: O(n * m)
7
+ // Decoding: O(n * m)
8
+ // 공간 복잡도
9
+ // Encoding: O(n * m),
10
+ // Decoding: O(n * m)
11
+ class Solution {
12
+
13
+ // 받아온 string 들을 한 문자열로 합침
14
+ // (문자열길이)#(문자열) 형식
15
+ public String encode (List <String > strs ) {
16
+ StringBuilder encodedStr = new StringBuilder ();
17
+ for (String str : strs ) {
18
+ encodedStr .append (str .length ()).append ('#' ).append (str );
19
+ }
20
+ return encodedStr .toString ();
21
+ }
22
+
23
+ // Decodes a single string to a list of strings
24
+ public List <String > decode (String s ) {
25
+ List <String > result = new ArrayList <>();
26
+ int i = 0 ;
27
+
28
+ while (i < s .length ()) {
29
+
30
+ int j = i ;
31
+ while (s .charAt (j ) != '#' ) { // # 문자 찾기
32
+ j ++;
33
+ }
34
+
35
+ // 문자열 길이 추출
36
+ int length = Integer .parseInt (s .substring (i , j ));
37
+
38
+ // 위에서 구한 문자열 길이만큼 문자열 추출
39
+ result .add (s .substring (j + 1 , j + 1 + length ));
40
+
41
+ // i 위치 변경
42
+ i = j + 1 + length ;
43
+ }
44
+
45
+ return result ;
46
+ }
47
+
48
+ }
You can’t perform that action at this time.
0 commit comments