482. License Key Formatting
1、原题:
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.
2、题目理解与解题思路
这道题目比较简单,大意是给你一个非空的字符串S,然后给你一个正整数K,将字符串(“-”不算)用“-”分割,除了第一段字符数可以小于K外,其它字段都要等于K。
那解题思路也就很简单了:
- 去除原字符串中的“-”字符。
- 计算字符串长度,计算其根据K可以划分为几段,其余数是多少(余数为第一段长度),若余数为0,则第一段长度为K。
- 根据处理过的字符串和步骤二中计算的结果构建新的字符串。
3、解题代码
public class Solution {
public String licenseKeyFormatting(String S, int K) {
S = S.toUpperCase();
//将“-”用“”替换,方便计算字符串长度
S = S.replaceAll("-","");
if (S.length() <= 0) {
return new String();
}
//计算余数
int remaider = S.length() % K;
//计算划分为几块
int groups = S.length() / K;
int setw;
StringBuilder s1 = new StringBuilder();
//若余数为0,第一块为K,否则为余数长度
if (remaider == 0) {
s1.append(S.substring(0, K));
setw = K-1;
} else {
groups++;
s1.append(S.substring(0, remaider));
setw = remaider-1;
}
//构建新的字符串
for (int i = 1; i < groups; i++) {
s1.append("-");
s1.append(S.substring(setw + 1, setw + K + 1));
setw = setw + K;
}
return s1.toString();
}
}