题意:
For this question, your program is required to process an input string containing only ASCII characters between ‘0’ and ‘9’, or between ‘a’ and ‘z’ (including ‘0’, ‘9’, ‘a’, ‘z’).
Your program should reorder and split all input string characters into multiple segments, and output all segments as one concatenated string. The following requirements should also be met,
1. Characters in each segment should be in strictly increasing order. For ordering, ‘9’ is larger than ‘0’, ‘a’ is larger than ‘9’, and ‘z’ is larger than ‘a’ (basically following ASCII character order).
2. Characters in the second segment must be the same as or a subset of the first segment; and every following segment must be the same as or a subset of its previous segment.
Your program should output string “<invalid input string>” when the input contains any invalid characters (i.e., outside the '0'-'9' and 'a'-'z' range).
样例输入aabbccdd 007799aabbccddeeff113355zz 1234.89898 abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee
abcdabcd 013579abcdefz013579abcdefz <invalid input string> abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa代码WA,得了90,不知道哪里错误。
思路,是先计算出每个字符出现的字数,然后根据次数,重组新的字符串输出。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
int length = s.length();
if(length<1){
System.out.println("");
return;
}
StringBuilder ret = new StringBuilder();
int[] a = new int[256];
for(int i=0;i<length;i++){
char c = s.charAt(i);
if((c>='0' && c<='9') || (c>='a' && c<='z')){
a[c]++;
}else{
System.out.println("<invalid input string>");
return;
}
}
boolean b = true;
while(b){
b = false;
for(int i=48;i<123;i++){
if(a[i]>0){
char c = (char)i;
ret.append(c);
a[i]--;
if(a[i]>0){
b=true;
}
}
}
}
System.out.println(ret.toString());
}
}
本文介绍了一个字符重组算法的设计思路,该算法接收包含特定ASCII字符('0'-'9'及'a'-'z')的字符串作为输入,并按严格递增顺序重新组织这些字符,形成多个片段。同时确保后续片段为前一个片段的子集。文章提供了实现该功能的Java代码示例。
882

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



