import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class StringCount {
private static int MAXLENGTH = 3;
public static void main(String[] args) {
String s = "cccdaaaaaabbbb";
new StringCount().count(s);
}
private static Map<String, Integer> map = new HashMap<String, Integer>();
void count(String s) {
for (int i = 1; i < =MAXLENGTH; i++) {
countStr(i, s);
}
sort();
}
private void countStr(int len, String s) {
for (int i = 0; i + len <= s.length(); i++) {
String temp = s.substring(i, i + len);
if (map.get(temp) == null) {
countStr1(temp, s);
} else {
continue;
}
}
}
private void countStr1(String temp, String s) {
if (null == map.get(temp))
map.put(temp, 0);
else
return;
while (s != null && !s.equals("")) {
if (s.startsWith(temp)) {
int t = map.get(temp);
map.put(temp, ++t);
}
s = s.substring(1);
}
}
static void sort() {
List<Entry<String, Integer>> mappingList = new ArrayList<Map.Entry<String, Integer>>(
map.entrySet());
// 通过比较器实现比较排序
Collections.sort(mappingList,
new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> entry1,
Map.Entry<String, Integer> entry2) {
if (entry1.getValue() == entry2.getValue()) {
return entry1.getKey().compareTo(entry2.getKey());
} else {
return entry2.getValue().compareTo(
entry1.getValue());
}
}
});
for (Map.Entry<String, Integer> mapping : mappingList) {
System.out.println(mapping.getKey() + ":" + mapping.getValue());
}
}
}
长度小于3的连续子串在原串中出现的次数,结果按照数量和字典排序
最新推荐文章于 2024-04-19 18:44:39 发布