일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- 누룽지소금빵
- 취미
- 코테
- 발더스게이트
- 눈알빠지겠네
- 발더스3
- 밥먹고
- 하스스톤
- 서울제빵소
- 미앤아이
- 발더스모드
- 메탈퍼즐
- 나쫌
- LeetCode
- DIY
- 송리단
- 노노그램
- 바질토마토뭐시기
- javascript
- 코딩테스트
- 알고리즘테스트
- 맛집
- 토이프로젝트
- 잠실새내
- 천등
- 뜨아거
- 3d퍼즐
- 게임
- 버즈2프로
- 메일우유
- Today
- Total
.Zzumbong
[leetCode/JS] 2047. Number of Valid Words in a Sentence 본문
문제 설명
A sentence consists of lowercase letters ('a'
to 'z'
), digits ('0'
to '9'
), hyphens ('-'
), punctuation marks ('!'
, '.'
, and ','
), and spaces (' '
) only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '
.
A token is a valid word if all three of the following are true:
- It only contains lowercase letters, hyphens, and/or punctuation (no digits).
- There is at most one hyphen
'-'
. If present, it must be surrounded by lowercase characters ("a-b"
is valid, but"-ab"
and"ab-"
are not valid). - There is at most one punctuation mark. If present, it must be at the end of the token (
"ab,"
,"cd!"
, and"."
are valid, but"a!b"
and"c.,"
are not valid).
Examples of valid words include "a-b."
, "afad"
, "ba-c"
,"a!"
, and "!"
.
Given a string sentence
, return the number of valid words in sentence
.
입출력 예
Example 1:
Input: sentence = "cat and dog"
Output: 3
Explanation: The valid words in the sentence are "cat", "and", and "dog".
Example 2:
Input: sentence = "!this 1-s b8d!"
Output: 0
Explanation: There are no valid words in the sentence.
"!this" is invalid because it starts with a punctuation mark.
"1-s" and "b8d" are invalid because they contain digits.
Example 3:
Input: sentence = "alice and bob are playing stone-game10"
Output: 5
Explanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing".
"stone-game10" is invalid because it contains digits.
Constraints
1 <= sentence.length <= 1000
sentence
only contains lowercase English letters, digits,' '
,'-'
,'!'
,'.'
, and','
.- There will be at least
1
token.
내 솔루션
- 조건 3가지에 대해서 합칠 수 있는건 합치고 혼자
'!', ',', '.'
이렇게 오는거는 따로 빼줬다. - 한줄로 하고 싶은데 어떻게 하는지 모르겠다.
REGEX
어렵.
var countValidWords = function(sentence) {
const arr = sentence.trim().split(' ')
let count = 0;
for(let i = 0; i < arr.length; i++) {
if(/^[a-z]+(-[a-z]+)?[\.!,]?$/.test(arr[i]) || /^[\.!,]$/.test(arr[i])) {
count++;
}
}
return count;
};
감상평
- 솔직히
regex
문제들은Test site
못열면 틀릴 각오 해야하는거 아닌가 싶다. regex
관련 문법들을 다시 공부해봐야하나 너무 어렵다.
'coding test > leetCode' 카테고리의 다른 글
[leetCode/JS] 5. Longest Palindromic Substring (0) | 2022.11.24 |
---|---|
[leetCode/JS] 224. Basic Calculator (0) | 2022.11.24 |
[leetCode/JS] 9. Palindrome Number (0) | 2022.11.23 |
[lettCode/JS] 36. Valid Sudoku (0) | 2022.11.23 |
[leetCode/JS] 9. Palindrome Number (0) | 2022.11.23 |