Java solution, pretty straight-forward


  • 13
    A
    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        return strs.stream()
                   .map(s -> s.replace("/", "//").replace("*", "/*") + "*")
                   .collect(Collectors.joining()); 
    }
    
    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> res = new ArrayList<>();
        StringBuilder str = new StringBuilder();
        
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '/') {
                str.append(s.charAt(++i));
            } else if (s.charAt(i) == '*') { 
                res.add(str.toString()); 
                str.setLength(0); 
            } else {
                str.append(s.charAt(i));
            }
        }
        
        return res;
    }

  • 0
    M

    is this the lambdas? cool, upvoted


  • 0
    L

    stream is cool, but it's pretty slow comparing with traditional ways...
    Can any one explain this? Or maybe there is a better way to use it..


  • 2
    A

    @leonw007 Here is a blog post about the performance difference between streams and loops http://blog.takipi.com/benchmark-how-java-8-lambdas-and-streams-can-make-your-code-5-times-slower/
    Make sure you read to the end of it to see the true results.
    And here is another one which explains very well what streams were designed for https://jaxenter.com/java-performance-tutorial-how-fast-are-the-java-8-streams-118830.html.
    tl;dr Streams make your code more functional and arguably better describe what your code is doing. They are equally fast for operations on collections of non-primitive objects as regular loops. The big motivation of having streams, to be precise parallelStreams, is that they simplify the execution of long iterations on multiple processes, which makes them noticeably faster than running the entire iteration on a single process. Other than that, it's a stylistic choice if you are into functional languages, I used them while I was transitioning to Scala and wanted to get a good hang of them.


Log in to reply
 

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