微软2014实习生及秋令营技术类职位在线测试-1_String reorder

时间:2021-07-05 19:25:21

微软2014实习生及秋令营技术类职位在线测试

题目1 : String reorder


时间限制:10000ms
单点时限:1000ms内存限制: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.


样例输入
aabbccdd
007799aabbccddeeff113355zz
1234.89898
abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee
样例输出
abcdabcd
013579abcdefz013579abcdefz
<invalid input string>
abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa
package microsoft.stringReorder;

/**
* using HashMap and TreeSet
*/

import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str;
boolean isValid = true;
while(scan.hasNext()){
str = scan.next();
char[] ch = str.toCharArray();
int[] in = new int[ch.length];
//Examine the string that is valid or not.
for(int i=0; i<ch.length; i++){
in[i] = (int)ch[i];
if(in[i]<'0' || (in[i]>'9' && in[i]<'a') || in[i]>'z'){
isValid = false;
break;
}
}
if(isValid == false){
System.out.println("<invalid input string>");
isValid = true;
continue;
}
//Count the times of every char appeared
Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0; i<in.length; i++){
Integer temp = new Integer(in[i]);
if(hm.containsKey(temp)){
hm.put(temp, hm.get(in[i])+1);
}
else{
hm.put(temp, new Integer(1));
}
}
//Generate the new String
int k=0;
while(!hm.isEmpty()){
TreeSet<Integer> ts = new TreeSet<Integer>(hm.keySet()) ;
for(Iterator<Integer> iter = ts.iterator(); iter.hasNext();){
Integer tempInt = iter.next();
ch[k] = Character.valueOf((char)tempInt.intValue());
k++;
hm.put(tempInt, hm.get(tempInt)-1);
if(hm.get(tempInt)==0)
hm.remove(tempInt);
}
}
System.out.println(new String(ch));
}
scan.close();
}

}

这与昨天提交的代码稍有不同,主要改动在TreeSet。

昨天提交代码WA,得了90,不知道哪里错误。

好像好多用了java的,都是90。