我希望这个字符串按重复字符的降序排序。
例如我有这个字符串:" aabbbc"或者" ddfssskkk"。
所需的字符串是:" bbbaac"或" ssskkkddf"。
答案 0 :(得分:1)
我不会给你一个完整的答案,但希望能让你更容易:)
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] letterFrequency = new int['z' -'a']; //create an array of length 26 representing all lowercase letters
String s = "aabbbc";
for(int i = 0; i < s.length();i++) {
letterFrequency[s.charAt(i) -'a'] += 1; //adds 1 to the corresponding position in letterFrequency for each character in the string
}
System.out.println(Arrays.toString(letterFrequency));
}
}
<强>输出:强>
[2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
因此,请使用数组b
中有3 a
个2 c
&1和letterFrequency
来排序您的知识你想要的字符串:)
答案 1 :(得分:0)
这就是你所需要的,有很多字符串操作
private static String sortDuplicates(String in) {
StringBuilder sb = new StringBuilder(in);
char[] chars = in.toCharArray();
List<Integer> indexes = new ArrayList<Integer>();
int count = 0;
for (int i = 0; i < chars.length; i++) {
if (i < chars.length - 1 && chars[i] != chars[i + 1]) {
if (count == 0) {
sb.append(chars[i]);
indexes.add(i);
} else {
count = 0;
}
} else {
count++;
}
}
for (Object a : indexes.toArray()) {
sb.deleteCharAt((Integer) a);
}
char[] a = sb.toString().substring(0, sb.length() - indexes.size()).toCharArray();
Arrays.sort(a);
StringBuilder d = new StringBuilder(new String(a)).reverse();
return d.toString() + sb.substring(sb.length() - indexes.size());
}