Encode and Decode Strings

Published by

on

Problem

https://leetcode.com/problems/encode-and-decode-strings

Solution

// 1. encode 시 각 String 의 길이를 각 String 앞에 붙인다. 
// 2. 1번에서 붙인 길이 뒤에 '#' 와 같은 구분자를 추가한다. 
//  - 안그러면 String 자체가 숫자로 이루어져있을 때, 길이와 String 자체가 구분이 되지 않음!
// 3. decode 시 # 가 나올때까지 읽어서 길이를 추출하고 길이만큼 읽어서 List 에 추가한다.
public class Codec {

    private static String DELIMITER = "#";

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuilder result = new StringBuilder();
        int size = strs.size();
        for (int i=0;i<size;i++) {
            String str = strs.get(i);
            int strLen = str.length();
            result.append(strLen).append(DELIMITER).append(str);
        }

        return result.toString();
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> result = new ArrayList<>();
        int sLen = s.length();

        int start = 0;
        int end = 0;
        while(true) {
            if (end >= sLen) {
                break;
            }

            char c = s.charAt(end);
            if (DELIMITER.equals(String.valueOf(c))) {
                int len = Integer.valueOf(s.substring(start, end));
                String str = s.substring(end+1, end+1+len);
                result.add(str);

                end = end+1+len;
                start = end;
            } else {
                end++;
            }
        }

        return result;
    }


}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
  • DELIMITER 를 문자(#)와 길이를 함께 사용한다는 것이 포인트!
    • 길이만 사용했을 때는 문자 자체에 숫자가 포함되면 안되고
      문자만 사용했을 때는 문자 자체에 동일한 문자가 포함되면 안되므로!

Leave a comment