题意理解
给你一个字符串形式的电话号码 number 。number 由数字、空格 ' '、和破折号 '-' 组成。
请你按下述方式重新格式化电话号码。
首先,删除 所有的空格和破折号。
其次,将数组从左到右 每 3 个一组 分块,直到 剩下 4 个或更少数字。剩下的数字将按下述规定再分块:
2 个数字:单个含 2 个数字的块。
3 个数字:单个含 3 个数字的块。
4 个数字:两个分别含 2 个数字的块。
最后用破折号将这些块连接起来。注意,重新格式化过程中 不应该 生成仅含 1 个数字的块,并且 最多 生成两个含 2 个数字的块。
返回格式化后的电话号码。
问题分析
字符串处理,细心处理好边界条件。
对于不同长度的循环判断,单个循环不好判断,那就两个好了。
其他
https://leetcode-cn.com/problems/reformat-phone-number/
链接
class Solution {
public:
string reformatNumber(string number) {
string str;
for (char a : number) {
if ((a != ' ') && (a != '-')) {
str.push_back(a);
}
}
cout << str << endl;
int len = str.size();
string res;
if (len % 3 == 1) {
int i;
for (i = 0; i < len - 4; i ++) {
res.push_back(str[i]);
if (i != 0 && i % 3 == 2 && i != len - 1) {
res.push_back('-');
}
}
res.push_back(str[i]);
res.push_back(str[i+1]);
res.push_back('-');
res.push_back(str[i+2]);
res.push_back(str[i+3]);
}
else {
for (int i = 0; i < len; i++) {
res.push_back(str[i]);
if (i != 0 && i % 3 == 2 && i != len - 1) {
res.push_back('-');
}
}
}
return res;
}
};