8ms(beat 100%) Java Solution


  • 1
    D
    public class Codec {
    
    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuilder sb=new StringBuilder();
        for(String s:strs){
            sb=sb.append((char)(s.length()>>16)).append((char)s.length()).append(s);
        }
        return sb.toString();
    }
    
    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        ArrayList<String> result=new ArrayList();
        char[] cc=s.toCharArray();
        for(int i=0,num=0;i<cc.length;i=i+num){
            num=((0+cc[i])<<16)+cc[++i];
            result.add(new String(cc,++i,num));
        }
        return result;
    }
    

    }


  • 0
    M

    Can you please explain your logic? why are you shifting the length >> by 16?


  • 0
    Q

    @mananshah007 I guess this line:num=((0+cc[i])<<16)+cc[++i], actually get the length of string.

    sb.append((char)(s.length()>>16)).append((char)s.length()). I guess this line is to convert length of str into 2 chars.


  • 0
    Q

    @mananshah007
    I changed the code a little bit, there is no "length >> 16" and it works as well.
    public String encode(List<String> strs) {
    StringBuilder sb=new StringBuilder();
    for(String s:strs)
    sb=sb.append((char)s.length()).append(s);
    return sb.toString();}


  • 0
    L

    @QunWu Would that be safe if we just convert the length of the string to a char and then convert it back to an integer? What if we have a string with length for example, as 2^23?


Log in to reply
 

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