1694. Reformat the phone number
Easy difficulty 6
Give you a phone number in string form
number
.number
It consists of numbers, spaces' '
, and dashes'-'
.Please reformat the phone number as follows.
- First, delete all spaces and dashes.
- Next, the array from left to right with each group of three sub-blocks, until the remaining four or fewer digits. The remaining numbers will be divided into blocks according to the following rules:
- 2 numbers: a single block containing 2 numbers.
- 3 numbers: a single block with 3 numbers.
- 4 numbers: two blocks each containing 2 numbers.
Finally, connect the blocks with dashes. Note that during the reformatting process, a block containing only 1 number should not be generated, and a maximum of two blocks containing 2 numbers should be generated .
Return the formatted phone number.
Example 1:
输入:number = "1-23-45 6" 输出:"123-456" 解释:数字是 "123456" 步骤 1:共有超过 4 个数字,所以先取 3 个数字分为一组。第 1 个块是 "123" 。 步骤 2:剩下 3 个数字,将它们放入单个含 3 个数字的块。第 2 个块是 "456" 。 连接这些块后得到 "123-456" 。
Example 2:
输入:number = "123 4-567" 输出:"123-45-67" 解释:数字是 "1234567". 步骤 1:共有超过 4 个数字,所以先取 3 个数字分为一组。第 1 个块是 "123" 。 步骤 2:剩下 4 个数字,所以将它们分成两个含 2 个数字的块。这 2 块分别是 "45" 和 "67" 。 连接这些块后得到 "123-45-67" 。
Example 3:
输入:number = "123 4-5678" 输出:"123-456-78" 解释:数字是 "12345678" 。 步骤 1:第 1 个块 "123" 。 步骤 2:第 2 个块 "456" 。 步骤 3:剩下 2 个数字,将它们放入单个含 2 个数字的块。第 3 个块是 "78" 。 连接这些块后得到 "123-456-78" 。
Example 4:
输入:number = "12" 输出:"12"
Example 5:
输入:number = "--17-5 229 35-39475 " 输出:"175-229-353-94-75"
prompt:
2 <= number.length <= 100
number
Numbers and characters'-'
and' '
composition.number
Contains at least 2 digits in.
class Solution {
public:
string reformatNumber(string number) {
string buf, res;
for(auto ch: number){
if(isdigit(ch)){
buf.push_back(ch);
}
}
for(int i = 0; i < buf.size(); i++){
if(i != 0 && i % 3 == 0 && buf.size()-i > 1){
res.push_back('-');
}else if(i != 0 && i % 3 == 0 && i == buf.size()-1){
char ch = res.back();
res.pop_back();
res.push_back('-');
res.push_back(ch);
}
res.push_back(buf[i]);
}
return res;
}
};