您的位置:首页 > 产品设计 > UI/UE

leetcode 192. Word Frequency

2017-06-09 17:10 260 查看
题目: 192. Word Frequency

解答:

cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{ print $2, $1 }'


tr -s: truncate(缩短) the string with target string, but only remaining one instance (e.g. multiple whitespaces)

把多个连续的空格缩短为一个空格,即只保留一个空格, 然后用’\n’替换空格。

cat words.txt | tr -s ' ' 多个连续的空格缩短为一个
cat words.txt | tr -s ' ' '*' 缩短后的一个空格被 ‘*’替换
uniqu -c


sort: To make the same string successive so that uniq could count the same string fully and correctly.

uniq -c: uniq is used to filter out the repeated lines which are successive, -c means counting

sort -r: -r means sorting in descending order

awk ‘{ print 2,1 }’: To format the output, see here.

练习:

cat testfile


world

boy

hello

zero

zero

zero

alive

alive

先排序再去重,结果如下。

cat testfile | sort | uniq


alive

boy

hello

world

zero

先排序再计数,结果如下

cat testfile | sort | uniq -c


2 alive

1 boy

1 hello

1 world

3 zero
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode