LeetCode - 482. License Key Formatting - 思路详解 -C++

48 篇文章 0 订阅
43 篇文章 0 订阅

题目

Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced.

We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case.

So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above.

翻译

假设给定一个字符串,这个字符串代表软件的许可码。字符串由数字,字母以及分隔符组成。破折号分割字符串中的字母数字字符组。

我们希望每组的字符个数长度为K。除过第一组,可以比K短,但是必须只要有一个字符。为了满足要求,我们需要重新插入分割符。另外,所有小写字母必须转换成大些字母。

给定的字符串S没空,代表许可码。整数K表示,需要更具上述描述规则重新返回符合格式的许可吗。

思路

1,首先将所有的非分割符字符组成新的字符串S1
2,对S1进行处理,首先计算S1长度。如果S1 % K 不等于0,则需要对第一组进行特殊处理
3,然后对其他字符串,每隔K个插入’-‘即可。

代码

class Solution {
public:
    string getTheChar(string &s){
        string res = "";
        for(int i = 0; i < s.size(); i++){
            if(s[i] != '-'){
                res += s[i];
            }
        }
        return res;
    }

    string licenseKeyFormatting(string S, int K) {
        string res = "";
        string t = getTheChar(S);
        int charNum = t.size();
        int firstN = charNum%K;
        int time = charNum/K;
        int i = 0; 
        if(firstN){
            for(int j = 0; j < firstN;j++){
                if(isalpha(t[i]) && islower(t[i])){
                    res+= toupper(t[i]);
                }else{
                    res += t[i];
                }
                i++;
            }
            res += "-";
        }

        for(int j = 0; j < time; j++  ){
            for(int l = 0; l < K; l++){
                if(isalpha(t[i]) && islower(t[i])){
                    res+= toupper(t[i]);
                }else{
                    res += t[i];
                }
                i++;
            }
            res += "-";
        }
        res.pop_back();
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值