[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的许可证密钥,该字符串仅包含字 ...
随机推荐
- Kotlin反射实践操作详解
继续对反射进行实战. 获取构造方法: 先定义一个主构造方法,2个次构造方法,接下来咱们用反射来获取一下构造方法: 其结果: [fun <init>(kotlin.Int, kotlin.S ...
- BZOJ1123 [POI2008]BLO(割点判断 + 点双联通缩点size)
#include <iostream> #include <cstring> #include <cstdio> using namespace std; type ...
- Python通过xpath查找元素通过selenium读取元素信息
#coding:utf-8 from selenium import webdriver import time url ='http://www.baidu.com' driver = webdri ...
- BZOJ1499: 瑰丽华尔兹(单调队列)
pro: 给出一个n*m的地图,刚开始人在(x,y),每次给出一段区间(l,r,t),表示在时间[l,r]内,可以使人向4个方向(t)移动一格,或者不动.求最大可以移动多少格. sol: 考虑每一列( ...
- CF938G Shortest Path Queries 和 CF576E Painting Edges
这两道都用到了线段树分治和按秩合并可撤销并查集. Shortest Path Queries 给出一个连通带权无向图,边有边权,要求支持 q 个操作: x y d 在原图中加入一条 x 到 y 权值为 ...
- kvm创建windows2008虚拟机
virt-install -n win2008-fushi001 -r 16384 --vcpus=4 --os-type=windows --accelerate -c /data/kvm/imag ...
- AndroidStudio中Flutter打包APK
1.生成签名文件 在打包之前我们需要一个签名文件,证明文件的唯一性. keytool -genkey -v -keystore F:\APP\sign.jks -keyalg RSA -keysize ...
- uva12558埃及分数
1,看这全英文的题目就怪蛋疼的. 2,这输入也是奇奇怪怪的的.3,想要好好做题,理解做题,就得好好看题自己要理解吸收消化.单纯看别人的话,说实话并没有什么用处. 一,看题. 1,首先,枚举的分数肯定不 ...
- Python3中用pip离线安装
本文原创,转载请注明出处. Python3 中 离线安装 ① 生成已安装模块列表,默认存在C:\Users\Administrator下 pip freeze > requirements.tx ...
- 数论--扩展欧几里得exgcd
算法思想 我们想求得一组\(x,y\)使得 \(ax+by = \gcd(a,b)\) 根据 \(\gcd(a,b) = \gcd(b,a\bmod b)\) 如果我们现在有\(x',y'\) 使得 ...