返回一篇文章出现最多的英文单词及出现次数
腾讯imweb团队面试题:
方法一:使用两次循环,传统想法
function getAccount(str) { let array = str.split(' '), obj = {} for (let i = 0; i < array.length; i ++) { if (obj[array[i]] > 0) { obj[array[i]] = obj[array[i]] + 1 } else { obj[array[i]] = 1 } } let result = {str: '', account: 0} for (let key in obj) { if (result.account < obj[key]) { result.str = key result.account = obj[key] } } return result }
方法二:使用一次循环,使用2个对象存储
1 function account(str){ 2 let arr = str.split(' '),target = {str:'', account: 0}, store = {} 3 for (let i = 0; i < arr.length; i++) { 4 if (store[arr[i]]){ 5 store[arr[i]] = store[arr[i]] + 1 6 } else { 7 store[arr[i]] = 1 8 } 9 if (store[arr[i]] > target.account) { 10 target.str = arr[i] 11 target.account = store[arr[i]] 12 } 13 } 14 return target 15 }
方法调用:
1 let string = 'Christmas or Christmas Day is a holiday celebrating the birth of Jesus, the central figure of Christianity. It is traditionally celebrated on December 25 by most Western Christian churches. Although dating to probably as early as a.d. 200, the feast of Christmas did not become widespread until the Middle Ages. Aspects of celebration may include gift-giving, Christmas trees, display of Nativity sets, church attendance, the Father Christmas/Santa Claus myth, and family gatherings. The word Christmas is derived from Middle English Christemasse. It is a contraction meaning "Christ\'s mass". The name of the holiday is often shortened to Xmas because Roman letter "X" resembles the Greek letter X, an abbreviation for Christ.' 2 console.log(account(string)) 3 console.log(getAccount(string))
浙公网安备 33010602011771号