Valid Phone Numbers — LeetCode 193 Python Solution
EasyShell
- Problem
- #193
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers. You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx.
Example
987-123-4567 123 456 7890 (123) 456-7890
Python solution
Python
import re
def print_valid_numbers(path: str = "file.txt") -> None:
pattern = re.compile(r"^(\(\d{3}\) |\d{3}-)\d{3}-\d{4}$")
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.rstrip("\n")
if pattern.match(line):
print(line)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 193. Valid Phone Numbers?
- LeetCode 193. Valid Phone Numbers is rated Easy on LeetCode.
- What topics does LeetCode 193. Valid Phone Numbers cover?
- LeetCode 193. Valid Phone Numbers is tagged Shell on LeetCode.