Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit00a97d5

Browse files
authored
algorithm: percentage of letter (#1261)
1 parent5668e64 commit00a97d5

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

‎String/PercentageOfLetters.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
*@function percentageOfLetter
3+
*@description Return the percentage of characters in 'str'
4+
* that equal 'letter' rounded down to the nearest whole percent.
5+
* More info: https://leetcode.com/problems/percentage-of-letter-in-string/
6+
*@param {String} str
7+
*@param {String} letter
8+
*@returns {Number}
9+
*@example
10+
* const str = 'foobar', const letter = 'o'
11+
* percentageOfLetter(str, letter) // ===> 33
12+
*/
13+
constpercentageOfLetter=(str,letter)=>{
14+
if(typeofstr!=='string'||typeofletter!=='string'){
15+
thrownewError('Input data must be strings')
16+
}
17+
letletterCount=0
18+
// Iterate through the whole given text
19+
for(leti=0;i<str.length;i++){
20+
// Count how often the letter appears in the word
21+
letterCount+=str[i].toLowerCase()===letter.toLowerCase() ?1 :0
22+
}
23+
constpercentage=Math.floor((100*letterCount)/str.length)
24+
returnpercentage
25+
}
26+
27+
export{percentageOfLetter}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import{percentageOfLetter}from'../PercentageOfLetters'
2+
3+
describe('Percentage of Letters in a String',()=>{
4+
test('Calculate percent for lower case',()=>{
5+
expect(percentageOfLetter('foobar','o')).toEqual(33)
6+
expect(percentageOfLetter('aaabcd','a')).toEqual(50)
7+
})
8+
test('Calculate percent for upper case',()=>{
9+
expect(percentageOfLetter('foobar','o')).toEqual(33)
10+
expect(percentageOfLetter('aAabcd','a')).toEqual(50)
11+
})
12+
test('Throwing an exception',()=>{
13+
expect(()=>percentageOfLetter(100,'string')).toThrow()
14+
expect(()=>percentageOfLetter('string',true)).toThrow()
15+
})
16+
})

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp