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.

给一个字符串的注册码S,按要求对注册码进行格式化,每四个字符后面跟一个短横杠,每一部分的长度为K,第一部分长度可以小于K,所有字母必须是大写的。

解法:用数组记录字符,从后往前循环字符串,当前字符不是短横杠,就变大写加入数组,每隔四个字母加一个短横杠,最后在转换成字符串。

最重要的是判断4个字符的方法: if len(res) % (K + 1) == K

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();
}
}

Java:

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();
}   

Python: wo

class Solution(object):
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
res = []
for i in reversed(range(len(S))):
if S[i] != '-':
if len(res) % (K + 1) == K:
res.append('-')
res.append(S[i].upper()) return ''.join(s for s in reversed(res))  

Python: wo

class Solution(object):
def licenseKeyFormatting(self, S, K):
res = []
for c in reversed(S):
if c != '-':
if len(res) % (K + 1) == K:
res.append('-')
res.append(c.upper()) return ''.join(r for r in reversed(res))   

Python:

class Solution(object):
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
S = S.upper().replace('-','')
size = len(S)
s1 = K if size%K==0 else size%K
res = S[:s1]
while s1<size:
res += '-'+S[s1:s1+K]
s1 += K
return res 

Python:

class Solution:
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
S = S.replace("-", "").upper()[::-1]
return '-'.join(S[i:i+K] for i in range(0, len(S), K))[::-1]  

Python:

class Solution:
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
s = S[::-1].upper().replace('-', '')
return '-'.join(list(chunks(s, K)))[::-1]  

C++:

class Solution {
public:
string licenseKeyFormatting(string S, int K) {
string res = "";
for (int i = (int)S.size() - 1; i >= 0; --i) {
if (S[i] != '-') {
((res.size() % (K + 1) - K) ? res : res += '-') += toupper(S[i]);
}
}
return string(res.rbegin(), res.rend());
}
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 482. License Key Formatting 注册码格式化的更多相关文章

  1. 482 License Key Formatting 注册码格式化

    详见:https://leetcode.com/problems/license-key-formatting/description/ C++: class Solution { public: s ...

  2. [LeetCode] License Key Formatting 注册码格式化

    Now you are given a string S, which represents a software license key which we would like to format. ...

  3. 【leetcode】482. License Key Formatting

    problem 482. License Key Formatting solution1: 倒着处理,注意第一个字符为分隔符的情况要进行删除,注意字符的顺序是否正序. class Solution ...

  4. 482. License Key Formatting - LeetCode

    Question 482. License Key Formatting Solution 思路:字符串转化为char数组,从后遍历,如果是大写字母就转化为小写字母,如果是-就忽略,如果遍历了k个字符 ...

  5. 【LeetCode】482. License Key Formatting 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  6. 482. License Key Formatting

    static int wing=[]() { std::ios::sync_with_stdio(false); cin.tie(NULL); ; }(); class Solution { publ ...

  7. LeetCode_482. License Key Formatting

    482. License Key Formatting Easy You are given a license key represented as a string S which consist ...

  8. [Swift]LeetCode482. 密钥格式化 | License Key Formatting

    You are given a license key represented as a string S which consists only alphanumeric character and ...

  9. LeetCode算法题-License Key Formatting(Java实现)

    这是悦乐书的第241次更新,第254篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第108题(顺位题号是482).您将获得一个表示为字符串S的许可证密钥,该字符串仅包含字 ...

随机推荐

  1. 基于qemu和unicorn的Fuzz技术分析

    前言 本文主要介绍如果使用 qemu 和 unicorn 来搜集程序执行的覆盖率信息以及如何把搜集到的覆盖率信息反馈到 fuzzer 中辅助 fuzz 的进行. AFL Fork Server 为了后 ...

  2. Alpha冲刺(7/10)——2019.4.30

    所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(7/10)--2019.4.30 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...

  3. LINUX部署JAVA项目

    Tomcat 应用服务器搭建好 安装 tomcat 所需依赖或工具软件 sudo yum -y update sudo yum -y install wget java unzip 使用 wget 下 ...

  4. 合并K个有序链表

    方法一:采用归并的思想将链表两两合并,再将两两合并后的链表做同样的操作直到合并为只有一个新的链表为止. 归类的时间复杂度是O(logn),合并两个链表的时间复杂度是O(n),则总的时间复杂度大概是O( ...

  5. 神奇的 Object.defineProperty 解释说明

    原文 : https://segmentfault.com/a/1190000004346467?utm_source=tuicool&utm_medium=referral 这个方法了不起啊 ...

  6. EF实体类指定部分属性不映射数据库标记

    命名空间 ;using System.ComponentModel.DataAnnotations.Schema; 实体部分 public partial class Student { [NotMa ...

  7. Spark-源码分析01-Luanch Driver

    1.SparkSubmit.scala 什么是Driver 呢?其实application运行的进程 就是driver,也是我们所写的代码就是Driver. object DefaultPartiti ...

  8. laravel使用手札——使用PHPStorm提升开发速度

    laravel使用手札——使用PHPStorm提升开发速度 phpstormphplaravel  阅读约 4 分钟 PHPStorm安装 PHPStorm 使用手札——安装看这里 代码自动提示支持 ...

  9. navicat设置唯一

    https://blog.csdn.net/Song_JiangTao/article/details/82192189

  10. 洛谷 P4071 [SDOI2016]排列计数 题解

    P4071 [SDOI2016]排列计数 题目描述 求有多少种长度为 n 的序列 A,满足以下条件: 1 ~ n 这 n 个数在序列中各出现了一次 若第 i 个数 A[i] 的值为 i,则称 i 是稳 ...