일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- DWG
- attribute
- t1
- shiba
- 715. Range Module
- 43. Multiply Strings
- Protocol
- Python
- Python Implementation
- 30. Substring with Concatenation of All Words
- Regular Expression
- 프로그래머스
- data science
- 컴퓨터의 구조
- 파이썬
- concurrency
- kaggle
- Decorator
- LeetCode
- iterator
- Class
- 운영체제
- Substring with Concatenation of All Words
- 밴픽
- Generator
- 315. Count of Smaller Numbers After Self
- Convert Sorted List to Binary Search Tree
- 시바견
- Python Code
- 109. Convert Sorted List to Binary Search Tree
Archives
- Today
- Total
Scribbling
LeetCode: 65. Valid Number 본문
First solution is using regular expression.
Below is some useful patterns.
Integer: ^[+-]?\d+$
Flaot: ^[+-]?((\d+(\.\d*)?)|(\.\d+))$
Sicnetific notation: ^[+-]?((\d+(\.\d*)?)|(\.\d+))[eE][+-]?\d+$
class Solution:
def isNumber(self, s: str) -> bool:
import re
pat = re.compile('(^[+-]?((\d+(\.\d*)?)|(\.\d+))$)|(^[+-]?((\d+(\.\d*)?)|(\.\d+))[eE][+-]?\d+$)')
return re.match(pat, s)
Second solution is Deterministic Finite Automation (DFA).
DFA is very similar to finite state machine.
Below is the graph to solve this problem.
class Solution:
def isNumber(self, s: str) -> bool:
dfa = [
{"sign": 2, "dot": 3, "digit": 1},
{"digit": 1, "expo": 5, "dot": 4},
{"digit": 1, "dot":3},
{"digit": 4},
{"digit": 4, "expo": 5},
{"sign": 6, "digit": 7},
{"digit": 7},
{"digit": 7},
]
current_state =0
for char in s:
typ = ''
if char.isdigit():
typ = 'digit'
elif char == '.':
typ = 'dot'
elif char in ['e', 'E']:
typ = 'expo'
elif char in ['+', '-']:
typ = 'sign'
else:
return False
if typ not in dfa[current_state]:
return False
current_state = dfa[current_state][typ]
return current_state in [1, 4, 7]
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 109. Convert Sorted List to Binary Search Tree (0) | 2022.01.26 |
---|---|
LeetCode: 302. Smallest Rectangle Enclosing Black Pixels (0) | 2022.01.25 |
LeetCode: 30. Substring with Concatenation of All Words (0) | 2022.01.17 |
LeetCode: 27. Remove Element (0) | 2022.01.17 |
LeetCode: 454. 4Sum II (0) | 2022.01.16 |