【发布时间】:2018-09-11 01:26:00
【问题描述】:
这是挑战:
您将获得一个以字符串 S 表示的许可证密钥,该字符串仅包含字母数字字符和破折号。字符串由 N 个破折号分成 N+1 个组。
给定一个数字 K,我们希望重新格式化字符串,使每个组恰好包含 K 个字符,除了第一组可能比 K 短,但仍必须包含至少一个字符。此外,必须在两组之间插入破折号,并且所有小写字母都应转换为大写。
给定一个非空字符串 S 和一个数字 K,根据上述规则格式化字符串。
示例 1:
输入:S =“5F3Z-2e-9-w”,K = 4 输出:“5F3Z-2E9W”
说明:字符串 S 被分成两部分,每部分有 4 个字符。 请注意,两个额外的破折号不是必需的,可以删除。
示例 2:
输入:S =“2-5g-3-J”,K = 2 输出:“2-5G-3J”
解释:字符串 S 被分成三部分,除了第一部分,每部分有 2 个字符,因为它可以像上面提到的那样更短。
注意:
1) 字符串 S 的长度不会超过 12,000,并且 K 是一个正整数。
2) 字符串 S 仅由字母数字字符(a-z 和/或 A-Z 和/或 0-9)和破折号( -)。
3) 字符串 S 非空。
这是我的代码:
public static String licenseKeyFormatting(String S, int Key) {
String cleaned = S.replaceAll("[\\-]", "").toUpperCase();
String result = "";
int currentPos = 0;
//IF EVENLY SPLIT
if ( (cleaned.length() % Key) == 0 ) {
int numGroups = cleaned.length()/Key;
for(int i = 0; i < numGroups; i++) {
for (int k =0; k < Key; k++) {
char currentLetter = cleaned.charAt(currentPos++);
result = result + currentLetter;
}
if (i != (numGroups - 1)) {
result = result + "-";
}
}
}
else {
int remainder = cleaned.length() % Key;
for (int i = 0; i < remainder; i++) {
char currentLetter = cleaned.charAt(currentPos++);
result = result + currentLetter;
}
if(remainder == cleaned.length()) {
return result;
}
else {
result = result + "-";
}
int numGroups =( (cleaned.length() - remainder)/Key);
for (int i = 0; i < numGroups; i++) {
for (int k =0; k < Key; k++) {
char currentLetter = cleaned.charAt(currentPos++);
result = result + currentLetter;
}
if (i != (numGroups - 1)) {
result = result + "-";
}
}
}
//IF NOT EVENLY SPLIT
return result;
}
当我在我的计算机上运行它时,它运行良好。当我在 leetcode 上运行它时,在输入 44151 个字符和“1”作为键的字符串时,它会给我一个“超出时间限制”错误。当我在 IDE 上运行相同的输入时,它工作正常,但在 LeetCode 上却不行。可能是什么错误?我怎样才能使它更有效率?
【问题讨论】:
-
请提供挑战,而不是链接到挑战。当链接变得过时时,我们真的很讨厌它!
标签: java string performance time string-formatting