题目 #
You are given a phone number as a string number. number consists of digits, spaces ’ ‘, and/or dashes ‘-’.
You would like 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 there are 4 or fewer digits. The final digits are then grouped as follows:
- 2 digits: A single block of length 2.
- 3 digits: A single block of length 3.
- 4 digits: Two blocks of length 2 each.
The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.
Return the phone number after formatting.
思路1 #
分析 #
- 自己想的,保留一个数组,如果大于4个,直接拆出前三个加一个
-
- 最后如果剩余4个,拆成
22-22
,剩余不足4个,直接拼接到后面
代码实现 #
1func reformatNumber(number string) (result string) {
2 var addStr []byte
3 for i := range number {
4 if number[i] == ' ' || number[i] == '-' {
5 continue
6 }
7 addStr = append(addStr, number[i])
8 if len(addStr) > 4 {
9 result += string(addStr[:3]) + "-"
10 addStr = addStr[3:]
11 }
12 }
13 if len(addStr) == 4 {
14 result += string(addStr[:2]) + "-" + string(addStr[2:])
15 } else {
16 result += string(addStr)
17 }
18 return
19}
思路2 #
分析 #
- 直接三个三个拼接一个
-
- 最后判断,最后一位是
-
,删掉 - 如果倒数第二位是
-
,和倒数第三位交换值
代码实现 #
1func reformatNumber(number string) string {
2 addStr := make([]byte, 0, 4)
3 result := make([]byte, 0, len(number))
4 for i := range number {
5 if number[i] == ' ' || number[i] == '-' {
6 continue
7 }
8 addStr = append(addStr, number[i])
9 if len(addStr) == 3 {
10 addStr = append(addStr, '-')
11 result = append(result, addStr...)
12 addStr = addStr[:0]
13 }
14 }
15 result = append(result, addStr...)
16 if result[len(result)-1] == '-' {
17 return string(result[:len(result)-1])
18 } else if len(result) > 4 && result[len(result)-2] == '-' {
19 result[len(result)-2] = result[len(result)-3]
20 result[len(result)-3] = '-'
21 }
22 return string(result)
23}