Skip to content

Commit 57f1c62

Browse files
authored
Create 2047-number-of-valid-words-in-a-sentence.js
1 parent ec07531 commit 57f1c62

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {string} sentence
3+
* @return {number}
4+
*/
5+
const countValidWords = function(s) {
6+
const arr = s.split(' ')
7+
let res = 0
8+
for(const e of arr) {
9+
if(e.trim() && valid(e.trim())) res ++
10+
}
11+
return res
12+
};
13+
14+
function valid(e) {
15+
const zi = '0'.charCodeAt(0), ni = '9'.charCodeAt(0)
16+
const len = e.length
17+
for(const el of e) {
18+
if(el.charCodeAt(0) >= zi && el.charCodeAt(0) <= ni) return false
19+
}
20+
const num = (p, n) => (p >= 'a' && p <= 'z') && (n >= 'a' && n <= 'z')
21+
const hi = e.indexOf('-')
22+
if(hi !== -1) {
23+
if(hi === 0 || hi === e.length - 1 || e.indexOf('-', hi + 1) !== -1 || !num(e[hi - 1], e[hi + 1])) return false
24+
}
25+
26+
const p1 = e.indexOf('!')
27+
if(p1 !== -1) {
28+
if((len > 1 && p1 !== e.length - 1) || e.indexOf('-', p1 + 1) !== -1) return false
29+
}
30+
31+
const p2 = e.indexOf('.')
32+
if(p2 !== -1) {
33+
if((len > 1 && p2 !== e.length - 1) || e.indexOf('-', p2 + 1) !== -1) return false
34+
}
35+
36+
const p3 = e.indexOf(',')
37+
if(p3 !== -1) {
38+
if((len > 1 && p3 !== e.length - 1) || e.indexOf('-', p3 + 1) !== -1) return false
39+
}
40+
41+
return true
42+
}

0 commit comments

Comments
 (0)