EasyNo. 0193
Valid Phone Numbers — LeetCode 193 Python Solution
- Topics
- Shell
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0192 | Word Frequency | Medium |
| 0194 | Transpose File | Medium |
| 0195 | Tenth Line | Easy |
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
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.