Leetcode 1694. Reformat Phone Number
You are given a phone number in the form of a string number
. number
consists of digits, spaces ' '
, and/or dashes '-'
. You want to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until only 4 or fewer digits are left. After that, the reformatting is done as follows:
Return the phone number after reformatting.
' '
and dashes '-'
from the string.public class Solution {
public String reformatNumber(String number) {
// Step 1: Remove spaces and dashes
StringBuilder digits = new StringBuilder();
for (char ch : number.toCharArray()) {
if (Character.isDigit(ch)) {
digits.append(ch);
}
}
// Step 2: Reformat digits into blocks of length 3 or 2
int length = digits.length();
StringBuilder result = new StringBuilder();
int i = 0;
// Process chunks of 3 until the remaining characters are handled
while (length - i > 4) {
result.append(digits.substring(i, i + 3));
result.append("-");
i += 3;
}
// Handle the last 4 or fewer characters
if (length - i == 4) {
result.append(digits.substring(i, i + 2));
result.append("-");
result.append(digits.substring(i + 2));
} else {
result.append(digits.substring(i));
}
return result.toString();
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.reformatNumber("1-23-45 6")); // Output: "123-456"
System.out.println(sol.reformatNumber("123 4-567")); // Output: "123-45-67"
System.out.println(sol.reformatNumber("123 4-5678")); // Output: "123-456-78"
System.out.println(sol.reformatNumber("12")); // Output: "12"
System.out.println(sol.reformatNumber("--17-5 229 35-39475 ")); // Output: "175-229-353-94-75"
}
}
The time complexity of this solution is O(n) where n
is the length of the input string number
. This is because:
This approach is efficient and runs in linear time with respect to the length of the input.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?