字符串分割
给定一个非空字符串S,其被N个‘-’分隔成N+1的子串,给定正整数K,要求除第一个子串外,其余的子串每K个字符组成新的子串,并用‘-’分隔。对于新组成的每一个子串,如果它含有的小写字母比大写字母多,则将这个子串的所有大写字母转换为小写字母;反之,如果它含有的大写字母比小写字母多,则将这个子串的所有小写字母转换为大写字母;大小写字母的数量相等时,不做转换。 输入描述: 输入为两行,第一行为参数K,第二行为字符串S。 输出描述: 输出转换后的字符串。
- 示例1
- 输入
- 3
- 12abc-abCABc-4aB@
- 输出
- 12abc-abc-ABC-4aB-@
- 说明:子串为12abc、abCABc、4aB@,第一个子串保留,后面的子串每3个字符一组为abC、ABc、4aB、@,abC中小写字母较多,转换为abc,ABc中大写字母较多,转换为ABC,4aB中大小写字母都为1个,不做转换,@中没有字母,连起来即12abc-abc-ABC-4aB-@
- 示例2
- 输入
- 12
- 12abc-abCABc-4aB@
- 输出
- 12abc-abCABc4aB@
- 说明:子串为12abc、abCABc、4aB@,第一个子串保留,后面的子串每12个字符一组为abCABc4aB@,这个子串中大小写字母都为4个,不做转换,连起来即12abc-abCABc4aB@
直接暴力解法,本题主要考察业务水平,不考虑算法复杂度直接搞定。
public static void main(String[] args) {
int n=12;
String content="12abc-abCABc-4aB@";
StringBuilder result = new StringBuilder();
int index = content.indexOf("-"); // Find the index of the first occurrence of "-"
if (index == -1) {
System.out.println(content);
}
result.append(content, 0, index + 1);
String suffix = content.substring(index + 1);// Extract substring starting from the character after "-"
suffix = suffix.replaceAll("-", "");
char[] chars = suffix.toCharArray();
StringBuilder sb = new StringBuilder();
int i= 1;
for (char a:chars) {
sb.append(a);
if (i%n==0||i==chars.length){
Integer type = checkType(sb.toString());
String sharding;
if (type==0){
sharding = sb.toString().toUpperCase();
}else if (type==1){
sharding = sb.toString().toLowerCase();
}else {
sharding = sb.toString();
}
if (i==chars.length){
result.append(sharding);
}else {
result.append(sharding).append("-");
}
sb=new StringBuilder();
}
i++;
}
System.out.println(result);
}
/**
* 根据n,计算其中大小写字母的个数
* @param suffix
* @return 0-大写多 1-小写多 2-一样多
*/
private static Integer checkType(String suffix){
char[] chars = suffix.toCharArray();
int upCount = 0;
int lowCount = 0;
for (char a:chars) {
if (Character.isUpperCase(a)){
upCount++;
}else if (Character.isLowerCase(a)){
lowCount++;
}
}
if (upCount>lowCount){
return 0;
}else if (upCount==lowCount){
return 2;
}else {
return 1;
}
}