[LeetCode] 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:
- 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.
给一个字符串的注册码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 注册码格式化的更多相关文章
- 482 License Key Formatting 注册码格式化
详见:https://leetcode.com/problems/license-key-formatting/description/ C++: class Solution { public: s ...
- [LeetCode] License Key Formatting 注册码格式化
Now you are given a string S, which represents a software license key which we would like to format. ...
- 【leetcode】482. License Key Formatting
problem 482. License Key Formatting solution1: 倒着处理,注意第一个字符为分隔符的情况要进行删除,注意字符的顺序是否正序. class Solution ...
- 482. License Key Formatting - LeetCode
Question 482. License Key Formatting Solution 思路:字符串转化为char数组,从后遍历,如果是大写字母就转化为小写字母,如果是-就忽略,如果遍历了k个字符 ...
- 【LeetCode】482. License Key Formatting 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 482. License Key Formatting
static int wing=[]() { std::ios::sync_with_stdio(false); cin.tie(NULL); ; }(); class Solution { publ ...
- LeetCode_482. License Key Formatting
482. License Key Formatting Easy You are given a license key represented as a string S which consist ...
- [Swift]LeetCode482. 密钥格式化 | License Key Formatting
You are given a license key represented as a string S which consists only alphanumeric character and ...
- LeetCode算法题-License Key Formatting(Java实现)
这是悦乐书的第241次更新,第254篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第108题(顺位题号是482).您将获得一个表示为字符串S的许可证密钥,该字符串仅包含字 ...
随机推荐
- 《BUG创造队》第九次团队作业:Beta冲刺与验收准备
项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验十三 团队作业9:Beta冲刺与团队项目验收 团队名称 BUG创造队 作业学习目标 (1)掌握软件黑盒测试技术:(2)学 ...
- 绑定事件 .on("click",function(){})和.click(function(){})
1.$(element).click(function(){ }) 2.$(element).on("click",function(){ }) 在一般的情况之下第1种和第2种没什 ...
- [CSS3] Use media query to split css files and Dark mode (prefers-color-scheme: dark)
Dark Mode: :root { --text-color: #000; --background-color: #fff; } body { color: var(--text-color); ...
- [Javascript] Check Promise is Promise
const isPromise = obj => Boolean(obj) && typeof obj.then === 'function'; This can be a to ...
- Selenium ChromeDriver与Chrome版本映射表(更新到v77)
ChromeDriver版本 支持的Chrome版本 v77.0.3865.40 v77 v76.0.3809.126 v76 v75.0.3770.140 v75 v74 v74 v73 v73 v ...
- Python 03 pip 的安装和使用
原文:https://www.runoob.com/w3cnote/python-pip-install-usage.html 原文:https://www.jianshu.com/p/2be68ef ...
- MQTT 遗嘱使用
大部分人应该有这个需求: 我想让我的APP或者上位机或者网页一登录的时候获取设备的状态 在线还是离线 设备端只需要这样设置 注意:MQTT本身有遗嘱设置 所以大家可以设置遗嘱 ,注意哈,发布的主题 ...
- 原生 ajax 请求
ajax 即 Asynchronous Javascript And XML,AJAX 不是一门的新的语言,而是对现有持术的综合利用.本质是在 HTTP 协议的基础上以异步的方式与服务器进行通信. 异 ...
- 【loj3123】【CTS2019】重复
题目 给出一个长度为\(n\)的串\(s\),询问有多少个长度为\(m\)的串\(t\) 满足 \(t\) 的无限循环串存在一个长度为\(n\)且比\(s\)字典序严格小的子串 $ n , m \le ...
- WAMP 3.1.0 APACHE 2.4.27 从外网访问
想测试一下从外网访问自己的电脑,找了一圈,网上教程都是修改APACHE 的 httpd.conf,经过1小时的摸索,发现完全不对. 正真的方法是修改httpd-vhost.conf,需要修改2处: 1 ...