Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced.
We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case.
So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above.
Example 1:
Input: S = "2-4A0r7-4k", K = 4 Output: "24A0-R74K" Explanation: The string S has been split into two parts, each part has 4 characters.
Example 2:
Input: S = "2-4A0r7-4k", K = 3 Output: "24-A0R-74K" Explanation: The string S has been split into three parts, each part has 3 characters except the first part as it could be shorter as said 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.
我个人觉得这一题没有到Medium的难度,没有什么思维难度,会写代码就会做,主要是细节上可能会出现一些问题,下面给出两种方法:
方法一:
遍历法,按照的题目的要求,从后往前遍历,设置两个变量,一个当前位置index,一个遍历了多少个字符count。遍历一个字符,index--,如果字符符合要求(小写变大写,去掉“-”,其他的直接照搬),就加一个字符到结果中,如果成功加入,count++;当count%K==0,这时候就有加入一个“-”,以此类推,直到结束。这种方法遍历一次即可,不过有几个地方需要注意一下:
- 需要注意到当原始字符串连续出现“-”,又遇到正好需要加入“-”时,循环可能重复加入“-”。这时候我引入一个boolean变量,只有当真的加入字符到结果字符串中时,把变量置为true,这样才把“-”加入结果,加入以后变成false,就不可能出现连续加入的情况
- 需要注意结果集为空的情况,也就是输入集全为“---”。
public class Solution {
public String licenseKeyFormatting(String S, int K) {
char[] cArr = S.toCharArray();
int nDiff = 'a' - 'A';
int nIndex = cArr.length - 1;
int nCount = 0;
StringBuilder sb = new StringBuilder();
boolean bNeedDash = false;
while (nIndex >= 0) {
if (cArr[nIndex] != '-') {
bNeedDash = true;
nCount++;
if (cArr[nIndex] >= 'a' && cArr[nIndex] <= 'z') {
sb.insert(0, (char) (cArr[nIndex] - nDiff));
} else {
sb.insert(0, (char) cArr[nIndex]);
}
}
if (nCount % K == 0 && bNeedDash) {
bNeedDash = false;
sb.insert(0, '-');
}
nIndex--;
}
return nCount % K == 0&&sb.length()>0 ? sb.substring(1) : sb.toString();
}
}
方法二:
public String licenseKeyFormatting(String S, int K) {
S = S.replaceAll("-", "").toUpperCase();
int nRes = S.length() % K;
StringBuilder sb = new StringBuilder(S);
int nIndex = nRes;
if (nRes == 0) {
nIndex = K;
}
while (nIndex < sb.length()) {
sb.insert(nIndex, '-');
nIndex++;
nIndex += K;
}
return sb.toString();
}