给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。
请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。
请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。
class Solution {
public static String reformat(String s) {
int num = 0;
int res = 0;
int length = s.length();
//1.字符串转换为字符串数组
String[] chars = new String[length];
for(int i = 0; i < s.length(); i++)
chars[i] = s.substring(i,i + 1);
//2.统计每种字符的个数
for(int i = 0; i < chars.length; i++){
if(chars[i].matches("[0-9]"))
num++;
}
res = s.length() - num;
//3.1判断字符数是否满足要求--不满足
if(Math.abs(num - res) > 1)
return "";
//3.2判断字符数是否满足要求--满足
//通过辅助空间存储两种字符
else{
String nums[] = new String[num];
String ress[] = new String[res];
int j = 0;
int k = 0;
for(int i = 0; i < chars.length; i++){
if(chars[i].matches("[0-9]"))
if(j < num - 1)
nums[j++] = chars[i];
else
nums[j] = chars[i];
else if(chars[i].matches("[a-z]"))
if(k < res - 1)
ress[k++] = chars[i];
else
ress[k] = chars[i];
}
//根据不同情况重新组合
String newS = "";
if(num > res){
for(int i = 0; i < num; i++) {
if(i != num - 1){
newS += nums[i];
newS += ress[i];
}else{
newS += nums[i];
}
}
}else if(num == res){
for(int i = 0; i < num; i++) {
newS += nums[i];
newS += ress[i];
}
}else{
for(int i = 0; i < res; i++) {
if(i != res -1){
newS += ress[i];
newS += nums[i];
}else{
newS += ress[i];
}
}
}
return newS;
}
}
}