Map character to Ascii Number in String


  • 0
    R

    For each character, use ascill number to represent, use '-' and ',' as seperator for characters in string and for different strings.

        // list("abc", "",null, "asd,$#",...) 
        // "97-98-99, "empty","null" ....."
    public class Codec {
    
        // Encodes a list of strings to a single string.
        public String encode(List<String> strs) {
            if(strs.size() == 0)    return null;
            StringBuilder strBuilder = new StringBuilder();
            for(int k = 0; k < strs.size(); k++) {
                String str = strs.get(k);
                if(str == null){
                    strBuilder.append("null");
                }
                else if(str.length() == 0){
                    strBuilder.append("empty");
                }
                else {
                    char[] ch = str.toCharArray();
                    for(int i = 0; i < ch.length; i++) {
                        strBuilder.append((int)ch[i]);
                        if(i != ch.length - 1)  strBuilder.append('-');
                    }
                }
                if(k != strs.size() - 1)    strBuilder.append(',');
            }
            return strBuilder.toString();
        }
    
        // list("abc", "",null, "asd,$#",...) 
        // "97-98-99, "empty","null" ....."
        
        // Decodes a single string to a list of strings.
        public List<String> decode(String s) {
            List<String> res = new ArrayList<>();
            if(s == null) return res;
            String[] strs = s.split(",");
            for(String str : strs){   // each string
                if(str.equals("null")){
                    res.add(null);
                    continue;
                }
                else if(str.equals("empty")){
                    res.add("");
                    continue;
                }
                String toAddString = "";
                String[] numbers = str.split("-");
                for(String eachNum : numbers) {   // each character
                    int asciiVal = Integer.valueOf(eachNum);
                    char c = (char)asciiVal;
                    toAddString += c;
                }
                res.add(toAddString);
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.