482. License Key Formatting

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:

  1. The length of string S will not exceed 12,000, and K is a positive integer.
  2. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
  3. String S is non-empty.

这个题要求将字符串格式化,第一部分允许至少有一个数字, 其他部分必须正好有k个数字,中间要有-连接,并将字符转化成大写。
个人觉得这个题很有代表性,是因为转化后的字符串第一部分是开放的,就是不确定有几个数字。
可以考虑下边几种情况:
  1. “2-5g-3-J": 这种情况好说,只要转化成2-5G3J即可;
  2. “2----5g-3-j”,这种情况需要考虑如果有连续的连接符要如何处理;
  3. “-2-5g-3-J”,这种情况需要考虑如果原字符串是以连接符开始,要如何处理;
  4. “------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());
    }
};

我个人从这个题中得出的经验是,如果遇到开放的部分,不妨从反方向开始解决问题,先解决一般情况,比如前两种情况,在解决特殊情况,就是后两种情况。。。突然感觉语言匮乏,无法表达我的理解。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值