1694. Reformat Phone Number
package LeetCode_1694 import java.util.* /** * 1694. Reformat Phone Number * https://leetcode.com/problems/reformat-phone-number/ * 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. Example 1: Input: number = "1-23-45 6" Output: "123-456" Explanation: The digits are "123456". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456". * */ class Solution { /* * solution: queue, Time:O(n), Space:O(n) * */ fun reformatNumber(number: String): String { if (number.length <= 2) { return number } val queue = LinkedList<Char>() for (c in number) { if (c.isDigit()) { queue.offer(c) } } val sb = StringBuilder() while (queue.size > 4) { sb.append(queue.pop()).append(queue.pop()).append(queue.pop()).append("-") } while (queue.size == 4) { sb.append(queue.pop()).append(queue.pop()).append("-") } //checking the rest of in queue while (queue.isNotEmpty()) { sb.append(queue.pop()) } return sb.toString() } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)