LeetCode 1694: Reformat Phone Number Solution
Master LeetCode problem 1694 (Reformat Phone Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1694. Reformat Phone Number
Problem Explanation
Explanation:
- Remove all spaces and dashes from the input phone number.
- Group the remaining digits into blocks of length 3 until there are 4 or fewer digits.
- Handle the remaining digits based on the number of digits left (2, 3, or 4).
Time Complexity: O(N) where N is the length of the input phone number string. Space Complexity: O(N) for the output phone number string.
:
Solution Code
class Solution {
public String reformatNumber(String number) {
StringBuilder sb = new StringBuilder();
for (char c : number.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
}
}
StringBuilder result = new StringBuilder();
int len = sb.length();
for (int i = 0; i < len; i += 3) {
if (len - i == 4) {
result.append(sb.substring(i, i + 2)).append("-").append(sb.substring(i + 2, i + 4));
break;
} else if (len - i <= 3) {
result.append(sb.substring(i));
break;
} else {
result.append(sb.substring(i, i + 3)).append("-");
}
}
return result.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1694 (Reformat Phone Number)?
This page provides optimized solutions for LeetCode problem 1694 (Reformat Phone Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1694 (Reformat Phone Number)?
The time complexity for LeetCode 1694 (Reformat Phone Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1694 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1694 in Java, C++, or Python.