|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: (Leetcode) 271 - String Encode and Decode |
| 4 | +categories: [스터디-알고리즘] |
| 5 | +tags: |
| 6 | + [ |
| 7 | + 자바, |
| 8 | + java, |
| 9 | + 리트코드, |
| 10 | + Leetcode, |
| 11 | + 알고리즘, |
| 12 | + algorithm, |
| 13 | + string, |
| 14 | + encode, |
| 15 | + url, |
| 16 | + url encode, |
| 17 | + ] |
| 18 | +date: 2024-05-29 13:00:00 +0900 |
| 19 | +toc: true |
| 20 | +--- |
| 21 | + |
| 22 | +기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. |
| 23 | + |
| 24 | +[https://neetcode.io/practice](https://neetcode.io/practice) |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +- 문제 |
| 29 | + - 유료 : [https://leetcode.com/problems/encode-and-decode-strings/](https://leetcode.com/problems/encode-and-decode-strings/) |
| 30 | + - 무료 : [https://neetcode.io/problems/string-encode-and-decode](https://neetcode.io/problems/string-encode-and-decode) |
| 31 | + |
| 32 | +문자열 배열을 하나의 문자열로 합치고, 다시 문자열 배열로 되돌리면 되는 문제이다. |
| 33 | + |
| 34 | +## 내가 작성한 풀이 |
| 35 | + |
| 36 | +url encoding 방식을 활용하였다. |
| 37 | + |
| 38 | +java에서는 기본적으로 URLEncoder, URLDecoder 클래스를 제공해주지만, 문제 내에서 사용하지 못하였기에 최소한으로 구현하여 대체하였다. |
| 39 | + |
| 40 | +먼저 ',' 에 대한 처리가 중요한데 ',' 의 경우 url encode 를 하면 '%2C' 로 변경된다. 해당 부분을 replace 처리해주도록 하였다. |
| 41 | +이때 기존에 '%' 라는 문자가 있는 케이스가 있을 것 같아서 '%' 를 '%25'로 변경해주었다. |
| 42 | + |
| 43 | +```java |
| 44 | +public String encode(List<String> strs) { |
| 45 | + StringBuilder sb = new StringBuilder(); |
| 46 | + for (String str : strs) { |
| 47 | + sb.append(str.replace("%", "%25").replace(",", "%2C")).append(","); |
| 48 | + } |
| 49 | + return sb.length() > 0 ? sb.toString() : ""; |
| 50 | +} |
| 51 | + |
| 52 | +public List<String> decode(String str) { |
| 53 | + List<String> decodedList = new ArrayList<>(); |
| 54 | + if (str.length() > 0) { |
| 55 | + int commaIndex = str.indexOf(","); |
| 56 | + while (commaIndex > -1) { |
| 57 | + decodedList.add(str.substring(0, commaIndex).replace("%2C", ",").replace("%25", "%")); |
| 58 | + str = str.substring(commaIndex + 1); |
| 59 | + commaIndex = str.indexOf(","); |
| 60 | + } |
| 61 | + } |
| 62 | + return decodedList; |
| 63 | +} |
| 64 | +``` |
| 65 | + |
| 66 | +### TC, SC |
| 67 | + |
| 68 | +시간 복잡도는 O(n)이고, 공간 복잡도는 O(n \* m)이다. (m은 각 문자열 길이의 평균) |
| 69 | + |
| 70 | +### 비슷한 방식 |
| 71 | + |
| 72 | +json stringify 를 이용해도 될 것 이다. |
0 commit comments