My AC solution(one pipe command but cost 20ms)


  • 2
    L
    grep -oE '[a-z]+' words.txt | sort | uniq -c | sort -r | awk '{print $2" "$1}' 
    

    but it costs 20ms.


  • 0
    C

    should be sort -nr


  • 0
    E

    Here i used sed to turn spaces to a new line and others are the same as yours.

    sed -r 's/\s+/\n/g' words.txt | grep -v "^$" | sort | uniq -c | sort -r | awk '{print $2" "$1}'
    

  • 0
    G

    Could you please explain what does parameter '-oE' mean? Thanks!


  • 0
    G

    Could you please explain what does 's/\s+/\n/g' mean?
    Does that mean change the spaces between words to \n(next line)?
    If so, what does the final 'g' mean?

    Thanks!


  • 0
    S

    @grandyang

    $ man grep
    ...
    Matcher Selection
    -E, --extended-regexp
    Interpret PATTERN as an extended regular expression (ERE, see
    below).
    ...
    -o, --only-matching
    Print only the matched (non-empty) parts of a matching line,
    with each such part on a separate output line.


  • 0
    S

    @grandyang

    "g" at the end of a pattern matches/replaces all occurrences on a line, not just the first occurrence .
    I would strongly recommend learning regex - it becomes very important when you're doing shell scripting, but also any language where you're parsing text.

    Try Rexegg's regex Quickstart tutorial or google "regex" for a whole variety of quick references, cheatsheets and tutorials.

    Have fun regexing. :)


Log in to reply
 

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