leetcode 482. License Key Formatting(Key码格式化)(C++和Java)

47 篇文章 0 订阅
9 篇文章 0 订阅

问题描述:

  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.


这里写图片描述

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.

利用C++和Java两种语言进行编程

C++中会用到如下string的函数

  • push_back(c):将元素添加到该字符串的末尾
  • empty():当前字符串是否为空
  • at(i):返回字符串下标为i处的字符的引用
  • back():返回字符串最后一个字符的引用
  • front():返回字符串第一个字符的引用
  • pop_back():删除字符串的最后一个字符
  • rbegin():返回一个逆向迭代器,指向字符串的最后一个字符
  • rend():返回一个逆向迭代器,指向字符串的开头(第一个字符的前一个位置)。

C++:

class Solution {
public:
    string licenseKeyFormatting(string S, int K) {
        string res = "";
        int len = S.size();
        int count = 0;
        for (int i = len - 1; i >= 0; i--) {
            char c = S[i];
            if (c == '-') continue;
            if (c >= 'a' && c <= 'z') c -= 32;
            res.push_back(c);
            count++;
            if (count % K == 0)
            {
                res.push_back('-');
            }
        }
        if (!res.empty() && res.back() == '-')
            res.pop_back();
        return string(res.rbegin(), res.rend());
    }
};

Java:

class Solution {
    public String licenseKeyFormatting(String S, int K) {
        StringBuilder sb = new StringBuilder();
        for(int i = S.length() - 1; i >= 0; i--){
            if(S.charAt(i) != '-')
                sb.append(sb.length() % (K + 1) == K ? '-' : "").append(S.charAt(i));
        }
        return sb.reverse().toString().toUpperCase();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值