You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings 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 all lowercase letters should be converted to uppercase.
Given a non-empty string S and a number K, format the string according to the rules described above.
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.
Note:
- The length of string S will not exceed 12,000, and K is a positive integer.
- String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
- String S is non-empty.
这个题要求将字符串格式化,第一部分允许至少有一个数字, 其他部分必须正好有k个数字,中间要有-连接,并将字符转化成大写。
个人觉得这个题很有代表性,是因为转化后的字符串第一部分是开放的,就是不确定有几个数字。
可以考虑下边几种情况:
- “2-5g-3-J": 这种情况好说,只要转化成2-5G3J即可;
- “2----5g-3-j”,这种情况需要考虑如果有连续的连接符要如何处理;
- “-2-5g-3-J”,这种情况需要考虑如果原字符串是以连接符开始,要如何处理;
- “------2-5g-3-J”,这种情况需要考虑当原字符串是以多个连续的连接符开始怎么处理。
因为转化后的字符串中第一部分是开放的,且不能带连接符,所以我们从原字符串末尾开始向前扫描,遇到连接符直接跳过,当已经填充了k个字符就添加一个连接符。对于第四种情况,这么转化之后的结果是“J3G5-2-”,是目标字符串的反转,且最后一个字符是连接符,所以我们删掉最后的一个连接符,并将字符串反转,就是目标字符串,代码如下:
class Solution {
public:
string licenseKeyFormatting(string s, int k) {
int start = s.length() - 1;
string result;
int len = 0;
while (start >= 0) {
if (s[start] == '-') {
start--;
continue;
}
result += (char)toupper(s[start]);
len++;
if (len % k == 0) {
result += '-';
len = 0;
}
start--;
}
if (result.back() == '-') result.pop_back();
return string(result.rbegin(), result.rend());
}
};
我个人从这个题中得出的经验是,如果遇到开放的部分,不妨从反方向开始解决问题,先解决一般情况,比如前两种情况,在解决特殊情况,就是后两种情况。。。突然感觉语言匮乏,无法表达我的理解。。。