Java with "escaping"


  • 30

    Double any hashes inside the strings, then use standalone hashes (surrounded by spaces) to mark string endings. For example:

    {"abc", "def"}    =>  "abc # def # "
    {'abc', '#def'}   =>  "abc # ##def # "
    {'abc##', 'def'}  =>  "abc#### # def # "
    

    For decoding, just do the reverse: First split at standalone hashes, then undo the doubling in each string.

    public String encode(List<String> strs) {
        StringBuffer out = new StringBuffer();
        for (String s : strs)
            out.append(s.replace("#", "##")).append(" # ");
        return out.toString();
    }
    
    public List<String> decode(String s) {
        List strs = new ArrayList();
        String[] array = s.split(" # ", -1);
        for (int i=0; i<array.length-1; ++i)
            strs.add(array[i].replace("##", "#"));
        return strs;
    }
    

    Or with streaming:

    public String encode(List<String> strs) {
        return strs.stream()
                   .map(s -> s.replace("#", "##") + " # ")
                   .collect(Collectors.joining());
    }
    
    public List<String> decode(String s) {
        List strs = Stream.of(s.split(" # ", -1))
                          .map(t -> t.replace("##", "#"))
                          .collect(Collectors.toList());
        strs.remove(strs.size() - 1);
        return strs;
    }

  • 1
    R

    Hi @StefanPochmann , this is a cool solution! Thanks for sharing!

    But I don't exactly understand how you handle empty strings correctly. I mean I know what's happening but not exactly why. I looked up the documentation for what the limit argument to the split() method means, but don't exactly understand why you need to pass -1 here. Could you explain a bit please?


  • 0
    R

    really like it!


  • 0
    S
    This post is deleted!

  • 0
    S

    Hi @StefanPochmann , why does the code work in using " # ", but it doesn't work using " * "?


  • 2
    I

    @StellaYue , first parameter of String.split() function is a regular expression, that's why '*' is treated as a special character.


  • 1

    @rohan99 I happened to have the some question on the split() method, and I looked up from the Java Docs.

    From Document: If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

    so I think you can pass in any negative number in split() method, then it will not discard empty strings.


  • 0
    Y

    @tankztc what about input is NULL?What will split do at here? THX!


Log in to reply
 

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