Problem Description
Given a string, you use some letters or digits to creat a new string, this new string have three properties.
1. any two adjacent letter aren't the same.
2. the new string have the biggest length.
3. the new string have the biggest lexicographical ordering.
Input
The input consists of multiple test cases. Each test case contain a string, the string is consist of 'a'~'z', 'A' - 'Z' and '0' - '9'. the length of string is not exceed 500.
Output
For each case, print the new string.
Sample Input
2
abaa
001
Sample Output
aba
010
https://www.nowcoder.com/questionTerminal/573620c43a1b43efb53bd5fae90f08f7
The input consists of multiple test cases. Each test case contain a string, the string is consist of 'a'~'z', 'A' - 'Z' and '0' - '9'. the length of string is not exceed 500.
the length of string is not exceed 500.
其实字典排序这种事情有工具可以用。题目没有说要自己实现排序。我就用Arrays类里的sort来做了。
public String handle(String input){
char[] characters = input.toCharArray();
Arrays.sort(characters);
StringBuffer sb = new StringBuffer();
for (char c : characters) {
if (sb.length()>0) {
if (c != sb.charAt(sb.length()-1)) {
sb.append(c);
};
}else{
sb.append(c);
}
}
return sb.toString();
}
上面的回答对于题目理解得有问题。我把重复的直接过滤掉了。后来看到SampleOutput反思了一下。
下面这个应该才是正确的
public String handle(String input){
char[] characters = input.toCharArray();
Arrays.sort(characters);
StringBuffer sb = new StringBuffer();
StringBuffer temp = new StringBuffer();
for (char c : characters) {
if (sb.length()>0) {
if (c != sb.charAt(sb.length()-1)) {
sb.append(c);
}else{
temp.append(c);
}
}else{
sb.append(c);
}
}
if (temp.length()>0) {
String tempStr = handle(temp.toString());
if (sb.charAt(sb.length()-1) != tempStr.charAt(0)) {
sb.append(tempStr);
}
}
return sb.toString();
}
```