问题描述:
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开始的升序标识,每输出一次,标识设为-1。第一次输出标记为0的字符。
然后循环输出:
每次输出标识为正的字符,修改标识,间隔之后-1才能继续输出。记录每次循环中输出的个数,为0时停止。
代码如下
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
int *a;
while ( cin >> str ) {
int size_str = str.size();
sort(str.begin(), str.end());
bool invalid = false;
for ( int i = 0 ; i < size_str ; i ++) {
if ( !(((str[i] >= '0')&&(str[i] <= '9')) || ((str[i] >= 'a')&&(str[i] <= 'z')))) {
cout << "<invalid input string>\n";
invalid= true;
break;
}
}
if ( invalid == true ) continue;
a = new int [size_str];
a[0] = 0;
for ( int i = 1 ; i < size_str ; i++) {
a[i] = ( str[i] != str[i-1] ) ? 0 : a[i-1] + 1;
}
int count = 0 ;
for ( int i = 0 ; i < size_str ; i ++) {
if ( a[i] == 0 ) {
cout << str[i];
a[i] = -1;
count ++;
}
}
bool out_permit = false;
while ( count != 0 ) {
count = 0 ;
for ( int i = 0 ; i < size_str ; i ++) {
if ( a[i] < 0 ) out_permit = true;
if ( a[i] > 0 && out_permit ) {
cout << str[i];
a[i] = -1;
out_permit = false;
count++;
}
}
}
cout << endl;
delete [] a;
}
return 0;
}