Leetcode 1694. Reformat Phone Number
Given a string number
that consists of digits, spaces, and dashes, you need to reformat the string so that each group contains exactly three digits, except for the last group which could consider the remaining two digits. If there are exactly four digits left, they should be split into two groups of two digits. You should return the reformatted string.
number = "1-23-45 6"
Output: "123-456"
number = "123 4-567"
"123-45-67"
number
have leading or trailing spaces?
number
string?
Here is the C++ implementation of the above strategy:
#include <iostream>
#include <string>
std::string reformatNumber(std::string number) {
// Step 1: Remove non-numeric characters
std::string digits;
for (char c : number) {
if (isdigit(c)) {
digits += c;
}
}
// Step 2: Reformat the string
std::string result;
int n = digits.size();
int i = 0;
while (n > 0) {
if (n > 4) {
result += digits.substr(i, 3) + "-";
i += 3;
n -= 3;
} else if (n == 4) {
result += digits.substr(i, 2) + "-" + digits.substr(i + 2, 2);
break;
} else {
result += digits.substr(i, n);
break;
}
}
return result;
}
// Test cases
int main() {
std::string number1 = "1-23-45 6";
std::string number2 = "123 4-567";
std::string number3 = "123 4-5678";
std::string number4 = "12";
std::string number5 = "--17-5 229 35-39475 ";
std::cout << reformatNumber(number1) << std::endl; // Output: "123-456"
std::cout << reformatNumber(number2) << std::endl; // Output: "123-45-67"
std::cout << reformatNumber(number3) << std::endl; // Output: "123-456-78"
std::cout << reformatNumber(number4) << std::endl; // Output: "12"
std::cout << reformatNumber(number5) << std::endl; // Output: "175-229-353-947-5"
return 0;
}
n
is the length of the input string number
. This is because we are processing each character in the string twice: once to remove non-numeric characters and once more to reformat the string.This solution should handle the typical constraints and provide the desired phone number reformatting efficiently.
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?