https://leetcode.com/problems/valid-number/description/
Valid Number - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
오랜만에 포스팅하는 에러 코드 입니다!
이번에는 다양한 조건을 정규표현식, 그리고 boolean을 활용해 구현한 기발한 코드들을 Leetcode에서 가져왔습니다.
코드 자체가 창의적이고 인상깊어서 공부를 위한 기록으로 남깁니다 :)
1. 정규표현식 match 사용
class Solution:
def isNumber(self, s: str) -> bool:
return re.match(r"^[+-]?((\d+\.?\d*)|(\d*\.?\d+))([eE][+-]?\d+)?$",s)
match 를 사용해서 제시된 조건을 구문화 한 코드입니다.
2. 정규표현식 구조화를 통한 포맷팅
class Solution:
dec_number = r"[\+\-]?(\d+\.|\d+\.\d+|\.\d+)"
integer = r"[\+\-]?\d+"
regex = re.compile(rf"^({dec_number}|{integer})([eE]{integer})?$")
def isNumber(self, s: str) -> bool:
return bool(self.regex.match(s))
이 코드는 문제에 제시된 소수점이 있는 형태와 정수 형태를 분리해서 rf 정규표현식 포맷팅을 사용해서
훨씬 깔끔하게 식이 표현되고 이해되도록 했습니다.
3. True/False를 사용한 조건 구조화
class Solution:
def isNumber(self, s: str) -> bool:
num, exp, sign, dec = False, False, False, False
print(s,"-----------")
for c in s:
if c >= '0' and c <= '9': num = True
elif c == 'e' or c == 'E':
if exp or not num: return False
else: exp, num, sign, dec = True, False, False, False
elif c == '+' or c == '-':
if sign or num or dec: return False
else: sign = True
elif c == '.':
if dec or exp: return False
else: dec = True
else: return False
return num
이렇게도 표현이 가능하구나 했던 코드입니다.
숫자일때, exp(e혹은 E가 있을때), 양수음수 부호가 있을 때, 소수점이 있을 때 = > 4가지 경우의 수를 True/False화 해서
s라는 String 을 순회하면서 조건 부합 여부를 검색한 상위 1%의 코드인데요,,,,
많은 사람들이 정규표현식을 떠올릴 때 이렇게 boolean으로 조건을 만들 생각을 하는 발상이 배울 점이 많은 것 같습니다.
역시 코딩은 해도 해도 끝이 없네요 ㅎㅎㅎㅎㅎ 😀
Source: Leetcode
'‼ ERROR RECORD' 카테고리의 다른 글
Leetcode 2389. Longest Subsequence with Limited Sum (Binary Search, Prefix Sum) (1) | 2022.12.25 |
---|---|
Leetcode 37 스도쿠 문제 풀이 정리 (0) | 2022.11.19 |
Leetcode 295. Find Median (heapq 힙큐로 중간값 구하기) (0) | 2022.11.12 |
23 . Merge K sorted List(Linked List 정렬, Merge sort, 분할 정복) (0) | 2022.11.10 |
Leetcode 212. WordSearch 2 (0) | 2022.11.05 |
댓글