You are given a license key represented as a string s
that consists of only alphanumeric characters and dashes. The string is separated into n + 1
groups by n
dashes. You are also given an integer k
.
We want to reformat the string s
such that each group contains exactly k
characters, except for the first group, which could be shorter than k
but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.
Return the reformatted license key.
Example 1:
Input: s = "5F3Z-2e-9-w", k = 4 Output: "5F3Z-2E9W" Explanation: The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed.
Example 2:
Input: s = "2-5g-3-J", k = 2 Output: "2-5G-3J" Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
Constraints:
1 <= s.length <= 105
s
consists of English letters, digits, and dashes ‘-‘
.1 <= k <= 104
密钥格式化。
有一个密钥字符串 S ,只包含字母,数字以及 ‘-‘(破折号)。其中, N 个 ‘-‘ 将字符串分成了 N+1 组。
给你一个数字 K,请你重新格式化字符串,使每个分组恰好包含 K 个字符。特别地,第一个分组包含的字符个数必须小于等于 K,但至少要包含 1 个字符。两个分组之间需要用 ‘-‘(破折号)隔开,并且将所有的小写字母转换为大写字母。
给定非空字符串 S 和数字 K,按照上面描述的规则进行格式化。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/license-key-formatting
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道字符串的题。我的思路是首先用一个 stringbuilder 把所有不是破折号的char拿出来放在一起。拿出来之后,这里有一个 corner case 需要判断,因为有几个 test case 是只有破折号,没有char的。
其他正常的 case,我们再从右往左遍历,遍历的同时把字母改成大写并放入一个 stack 中,这里同时我们记得要一边数字母的个数一边加破折号。最后我们再把所有内容从stack中都pop出来,输出最后的字符串。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public String licenseKeyFormatting(String s, int k) { 3 // 收集所有的char 4 StringBuilder sb = new StringBuilder(); 5 for (char c : s.toCharArray()) { 6 if (c != ‘-‘) { 7 sb.append(c); 8 } 9 } 10 11 int len = sb.length(); 12 // corner case 13 if (len == 0) { 14 return ""; 15 } 16 17 // normal case 18 k %= len; 19 int kk = k; 20 Stack<Character> stack = new Stack<>(); 21 // 从右往左把char放入stack并改成大写 22 for (int i = len - 1; i >= 0; i--) { 23 stack.push(Character.toUpperCase(sb.charAt(i))); 24 kk--; 25 if (kk == 0 && i != 0) { 26 stack.push(‘-‘); 27 kk = k; 28 } 29 } 30 31 // 输出 32 StringBuilder res = new StringBuilder(); 33 while (!stack.isEmpty()) { 34 res.append(stack.pop()); 35 } 36 return res.toString(); 37 } 38 }
[LeetCode] 482. License Key Formatting
原文:https://www.cnblogs.com/cnoodle/p/14797873.html