Base64 alike solution


  • 0
    D
        // Encodes a list of strings to a single string.
        public  String encode(List<String> strs) {
            StringBuilder sb = new StringBuilder();
            for (String s: strs) {
                for (byte b: s.getBytes()) {
                    StringBuilder sb1 = new StringBuilder();
                    int mask=1;
                    for (int i=0;i<8;i++) {
                        mask = 1<<i;
                        if ((b&mask)==mask) sb1.append('a');
                        else sb1.append('b');
                    }
                    sb.append(sb1.reverse());
                }
                sb.append('c');
            }
            return sb.toString();
        }
    
        // Decodes a single string to a list of strings.
        public  List<String> decode(String s) {
            List<String> ret = new ArrayList<>();
            for (int si=0;si<s.length();si++) {
                int sj=si;
                while (s.charAt(sj)!='c') sj++;
                String seg = s.substring(si,sj);
                
                byte[] bytes = new byte[seg.length()/8];
                for (int i=seg.length()/8-1;i>=0;i--) {
                    int mask = 0;
                    for (int j=7;j>=0;j--) {
                        char ch = seg.charAt(i*8+j);
                        if (ch=='a') {
                            mask = 1 << (8-j-1);
                            bytes[i] |= mask;
                        }
                    }
                }
                ret.add(new String(bytes));
                si=sj;
            }
            return ret;
        }
    
    

Log in to reply
 

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