Encode and Decode Strings

weixin_33850890發表於2018-05-03

https://www.lintcode.com/zh-cn/problem/encode-and-decode-strings/

import java.util.ArrayList;
import java.util.List;

public class Solution {

    /*
     * @param strs: a list of strings
     * @return: encodes a list of strings to a single string.
     */
    public String encode(List<String> strs) {
        // write your code here
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strs.size(); i++) {
            String s = strs.get(i);

            if (i != 0) {
                sb.append(" ");
            }
            char[] chars = s.toCharArray();
            for (int j = 0; j < chars.length; j++) {
                char aChar = chars[j];
                sb.append((char) (aChar + 1));
            }
        }
        return sb.toString();
    }

    /*
     * @param str: A string
     * @return: dcodes a single string to a list of strings
     */
    public List<String> decode(String str) {
        // write your code here
        String[] split = str.split(" ");
        List<String> res = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            char[] chars = s.toCharArray();

            for (int j = 0; j < chars.length; j++) {
                char aChar = chars[j];
                chars[j] = (char) (aChar - 1);
            }
            res.add(String.valueOf(chars));
        }
        return res;
    }
}

相關文章