String reorder(一道自定义排序题)

来源:互联网 发布:李善兰 知乎 编辑:程序博客网 时间:2024/04/30 07:00

这是今年微软hihoCode的一道在线编程题,看到学长学姐们把题目贴出来,自己也拿来做一下。

描述如下:

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).


Input


Input consists of multiple cases, one case per line. Each case is one string consisting of ASCII characters.

Output


For each case, print exactly one line with the reordered string based on the criteria above.


样例输入
aabbccdd
007799aabbccddeeff113355zz
1234.89898
abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee
样例输出
abcdabcd
013579abcdefz013579abcdefz
<invalid input string>
abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa


我的思路:建立一个10+26数组,存放每个字符出现的次数,然后遍历,遇到不为零的就打印出来并把次数--。

代码如下:

public class Reorder {private boolean isValid(String str){char []temp=str.toCharArray();boolean isValid=true;for(char c:temp){if(c<'0'||c>'z'||(c>'9'&&c<'a')){isValid=false;    break;}}return isValid;}private String transform(String str){int[] str_count=new int[36];//存字符出现的次数char[] ch=str.toCharArray();for(int m=0;m<str_count.length;m++)str_count[m]=0;for(int i=0;i<ch.length;i++){if(ch[i]<'a')str_count[(ch[i]-'0')]+=1;elsestr_count[ch[i]-'0'-('a'-'9')+1]+=1;}StringBuilder sb=new StringBuilder();int j=str.length();while(j>0){//count不为0时就输出一次,count--,直至全部输出for(int n=0;n<str_count.length;n++){if(str_count[n]!=0){if(n<10)    sb.append((char)('0'+n));elsesb.append((char)('a'+n-10));str_count[n]--;j--;}}}String string=sb.toString();return string;}public void reorder(String str){if(isValid(str))System.out.println(transform(str));elseSystem.out.println("<invalid input string>");}public static void main(String[]args){String str1="aabbccdd";String str2="007799aabbccddeeff113355zz";String str3="1234.89898";String str4="abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee";Reorder reorder=new Reorder();reorder.reorder(str1);reorder.reorder(str2);reorder.reorder(str3);reorder.reorder(str4);}}


输出:

abcdabcd013579abcdefz013579abcdefz<invalid input string>abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa



然后在知乎上问了一些达人的解题思路,好吧,我只能说,路漫漫其修远兮。。。。。。。(看不懂)

htt@p://w@ww.zhihu.com/question/23384877(不让放链接,去掉@)

0 0
原创粉丝点击