模拟题
import java.util.ArrayList;
import java.util.List;
/**
* @author xnl
* @Description:
* @date: 2022/8/11 22:22
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
String s = "a0b1c2";
//String s = "covid2019";
System.out.println(solution.reformat(s));
}
public String reformat(String s) {
StringBuilder a = new StringBuilder(), b = new StringBuilder();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (Character.isDigit(c)) {
a.append(c - '0');
} else {
b.append(c);
}
}
int n = a.length(), m = b.length(), total = n + m;
if (Math.abs(n - m) > 1){
return "";
}
StringBuilder sb = new StringBuilder();
while (sb.length() != total){
if (n > m){ // 数字多字母少
sb.append(a.charAt( --n ));
} else if (n < m){ // 字母多数字少
sb.append( b.charAt(--m ));
} else {
// 如果是字符
if (sb.length() != 0 && sb.charAt(sb.length() - 1) >= 'a'){
// 添加数字
sb.append(a.charAt(--n));
}else {
// 不是字符添加字符
sb.append(b.charAt( --m ));
}
}
}
return sb.toString();
}
}

本文介绍了一种用于重新组织字符串中字符和数字的算法实现。通过该算法可以将输入字符串中的字符和数字分离,并按照一定规则交替排列,最终形成新的字符串。文章提供了一个具体的Java实现案例,包括如何处理不同长度的字符和数字部分。
563

被折叠的 条评论
为什么被折叠?



