Leetcode: Word Frequency (shell , awk)
来源:互联网 发布:快速掌握java语言 编辑:程序博客网 时间:2024/05/21 11:05
单词统计。仍然先贴代码,再讲我的思路:
# Read from the file words.txt and output the word frequency list to stdout.#!/bin/bashawk 'BEGIN{while(getline < "words.txt") { for(i=1;i<=NF;i++) { freq[$i]++; }}n = asort(freq, dest);for(word in freq) { reversefreq[freq[word]] = word;}for (j=n;j>=1;j--) { print reversefreq[dest[j]]" "dest[j];}}'
一、awk数组可以是按字符串取值,当然就想到用它,但是在其value递增时,要不要先初始化为0呢?另外,在判断第一个word在不在array的index里之前,是否需要声明array呢?awk数组不需要声明,且对value可以直接进行递增操作。awk数组是我见过的最强大的数组。
二、按空格分割用到简单的正则表达式,分隔符为一个或多个空格,则正则表达式就是:
" +"
所有的正则表达式规则都一样,Java的split函数,其参数也是可以用正则表达式的,例如:
String[] ssplit = s.split(" +");
也是分割一个或多个空格。不过awk使用$i取每一列的值时,已经有这样的能力,不用再用正则表达式了。
三、asort()函数会破坏原数组的index,所以我们将排序放到dest数组上去。dest数组保存着freq数组的由小到大的value,这时候我们将freq数组的key和value互换,得到reversefreq数组。这样,我们就能按照freq数组,取出相应的word了!这就是为什么题目里有这么一句:Don’t worry about handling ties, it is guaranteed that each word’s frequency count is unique.
总之,awk数组是我用过的最好用的数组了!
0 0
- Leetcode: Word Frequency (shell , awk)
- [Leetcode Shell]Word Frequency
- 【Leetcode Shell】Word Frequency
- leetcode-shell-192. Word Frequency
- [leetcode][bash] Word Frequency
- leetcode-192 Word Frequency
- LeetCode 192 Word Frequency
- Leetcode: Word Frequency
- [leetcode]Word Frequency
- leetcode 192. Word Frequency
- [Leetcode] 192. Word Frequency
- [Leetcode] Word Frequency的笔记
- [LeetCode] Word Frequency 单词频率
- Word Frequency
- Word Frequency
- Word Frequency
- Word Frequency
- shell 和 python3 :Word Frequency(leetcode192-t11.sh)
- android 初识ViewPager
- 我的IT学习笔记
- 去掉xcode源码末尾的空格
- Ubuntu Hadoop 2.6.0 单机版配置图文详解
- Linux常用命令
- Leetcode: Word Frequency (shell , awk)
- 理解矩阵(1,2,3)
- C++简单贪吃蛇实现
- mark-使用volley以及百度定位获取天气
- Qt信号与槽
- Linux Shell脚本攻略(1.5)
- 埃拉托色尼选筛法
- 给TableView设置背景图片
- HashMap存储的使用