[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的许可证密钥,该字符串仅包含字 ...
随机推荐
- php中函数的类型提示和文件读取功能
这个没有深入. <?php function addNumbers(int $a, int $b, bool $printSum): int { $sum = $a + $b; if ($pri ...
- appium+python自动化62-webview元素click失效问题解决
前言 Appium 在切换到 webview 后,正确定位到元素,但是click () 事件后界面无响应,脚本运行正常不会报错. 主要原因是:混合APP 时监听全用的是tap事件,不是click事件 ...
- spark-scala开发的第一个程序WordCount
package ***** import org.apache.spark.{SparkConf, SparkContext} object WordCount { def main(args: Ar ...
- node 日志 log4js 错误日志记录
SET DEBUG=mylog:* & npm start 原文出处:http://blog.fens.me/nodejs-log4js/ 1. 默认的控制台输出 我们使用express框架时 ...
- Centos7配置静态网卡
1.打开VMware,查看ifconfig 2.进入网卡编辑 [root@localhost ~]# cd /etc/sysconfig/network-scripts/ [root@localhos ...
- web开发——文件的上传和下载
众所皆知,web上传大文件,一直是一个痛.上传文件大小限制,页面响应时间超时.这些都是web开发所必须直面的. 本文给出的解决方案是:前端实现数据流分片长传,后面接收完毕后合并文件的思路. 实现文件夹 ...
- velero 备份、迁移 kubernetes 应用以及持久化数据卷
velero 是heptio 团队开源的kubernetes 应用以及持久化数据卷备份以及迁移的解决方案,以前的名字为ark 包含以下特性: 备份集群以及恢复 copy 当前集群的资源到其他集群 复制 ...
- 二八法则(The 80/20 Principle)
二八法则的定义:在任何一组事物中,最重要的只占其中一小部分,约20%,其余80%尽管占多数,却是次要的. 二八法则的例子:社会上20%的人占有80%的社会财富 20%的工厂有80%的产出 80%的利润 ...
- gulp+apache代理请求处理javascript跨域请求
apache设置(参考) 用 apache 的 mod_proxy 模块开启反向代理功能来实现: 1 修改 apache 配置文件 httpd.conf ,去掉以下两行前面 # 号 LoadModul ...
- 团队作业-Beta冲刺(4/4)
队名:软工9组 组长博客:https://www.cnblogs.com/cmlei/ 作业博客:https://edu.cnblogs.com/campus/fzu/SoftwareEngineer ...