1. 问题描述
给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。
请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。
请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。
2. 解题思路
特判:① 当字符串长度为1 时,即仅含一个字母或者数字时,直接返回原字符串;② 当字符串全部为数字或者全部为字母时,返回空串;③ 当且仅当字符串中的数字总数和字母总数的差值不超过 1 时,才能重新格式化字符串。
此外,当字符串中的字母总数大于数字总数时,新格式化的字符串的首位必须是字母,反之则为数字。
3. 实现代码
class Solution {
public String reformat(String s) {
int len = s.length();
int count = 0;
char[] charArr = s.toCharArray();
for (char c : charArr) {
if (Character.isDigit(c)) {
count++;
}
}
if (len == 1) {
return s;
} else if (count == 0 || count == len || Math.abs(len - 2 * count) > 1) {
return "";
} else {
StringBuffer res = new StringBuffer(s);
if (count > len / 2) {
for (int i = 0, j = 0; i < len && j < len; i++) {
if (Character.isDigit(s.charAt(i))) {
res.setCharAt(j, s.charAt(i));
j += 2;
}
}
for (int i = 0, j = 1; i < len && j < len; i++) {
if (!Character.isDigit(s.charAt(i))) {
res.setCharAt(j, s.charAt(i));
j += 2;
}
}
} else {
for (int i = 0, j = 0; i < len && j < len; i++) {
if (!Character.isDigit(s.charAt(i))) {
res.setCharAt(j, s.charAt(i));
j += 2;
}
}
for (int i = 0, j = 1; i < len && j < len; i++) {
if (Character.isDigit(s.charAt(i))) {
res.setCharAt(j, s.charAt(i));
j += 2;
}
}
}
return res.toString();
}
}
}
4. 提交记录
执行结果:通过
执行用时:4 ms, 在所有 Java 提交中击败了55.13%的用户
内存消耗:41.3 MB, 在所有 Java 提交中击败了85.26%的用户
通过测试用例:302 / 302