String reorder
题目如下:
Time Limit: 10000ms
Case Time Limit: 1000ms
Memory Limit: 256MB
Description
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.
Sample In
aabbccdd
007799aabbccddeeff113355zz
1234.89898
abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee
Sample Out
abcdabcd
013579abcdefz013579abcdefz
<invalid input string>
abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa
这一题是四道上机题中的第一道,题目的意思是输入一串字符串,然后按照其中0-9,a-z的顺序输出,输出一遍之后将剩余的字符串再按照这个顺序再次输出,直到字符串中的字符都输出为止。比如输入的字符串为aabbccdd,按照指定的排序第一次输出为abcd,此时字符串中还剩四个字符,再按照这个顺序输出,得到abcd,这个时候字符串中全部字符已经输出,所以最后的输出序列就是abcdabcd。
一般碰到这种涉及到字符出现次数相关的题目时,我都喜欢先考虑hash表,因为这个方法屡试不爽,这一题也不例外。这里可以构建一个0-9和a-z的为键的hash表,然后遍历字符串统计每个字符出现的次数生成hash表,接着要做的事情就是按照hash的键的顺序按序输出字符,每次输出完就将hash值减1,直到所有的字符输出完毕也就实现了该功能。除去构造hash表的时间,该方法的时间复杂度是O(N*M),其中N为字符的个数,M为hash表的大小。空间复杂度为O(1)。
##源代码