面試題查找重復元素並打印重復次數和重復位置,一頓懵逼,回來死磕寫下來,打印指定重復次數和最大次數,其他在此基礎上可以再更新
package sort;
import org.testng.annotations.Test;
import sun.org.mozilla.javascript.internal.ast.NewExpression;
import java.util.*;
/**
* Created by liangwei on 2018/10/18.
*/
public class SearchString {
/**
* 找出重復字符、記錄重復字符次數、記錄重復字符位置
* @param str
* @return map
*/
public Map get_str_count_index(String[] str){
Map<String,Map<Integer,ArrayList>> map = new HashMap<String ,Map<Integer,ArrayList>>();//key值記錄重復的字符串,value記錄出現的次數和位置
int i = 0;
for (String s:str ){
if (map.get(s)==null){
Map<Integer,ArrayList> count_where = new HashMap<Integer ,ArrayList>();//key值記錄重復字符串出現的次數,value記錄重復字符出現的位置
int count = 1;//重復字符串計數器
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);//重復字符串下標
count_where.put(count,list);
map.put(s,count_where);
i++;
}else {
for (int c:map.get(s).keySet()){
ArrayList index = map.get(s).get(c);
index.add(i);//增加出現index位置
c++;
map.get(s).put(c,index);//更新計數器和下標信息
map.get(s).remove(--c);//刪除掉之前的記錄信息
}
i++;
}
}
return map;
}
public void display(String[] arry) throws Exception{
if (arry==null){
throw new Exception("輸入數組為空,請重新輸入");
}
Map<String,HashMap<Integer,ArrayList>> map = get_str_count_index(arry);
ArrayList count = new ArrayList<Integer>();//存取所有字符串出現的次數
for (Map.Entry<String,HashMap<Integer,ArrayList>> key : map.entrySet()){//循環獲取記錄字符串重復次數和位置map
for (Map.Entry<Integer,ArrayList> map1 :key.getValue().entrySet()){//循環獲取記錄字符串重復次數
count.add(map1.getKey());
}
}
// Arrays.sort(count.toArray());
Collections.sort(count);//對集合排序,默認是升序,最后一個是重復次數最多的
//打印重復次數最多的元素信息
for (String key : map.keySet()){//循環獲取所有的重復字符串
for (int c:map.get(key).keySet()){//循環獲取重復字符串的次數
if (c == count.get(count.size()-1)){//和最大重復次數對比,相等就代表當前的字符串是重復次數最多的那個
System.out.printf("重復次數最多的字符串是:%s,重復次數%d,所在位置:%s\n",key,c,map.get(key).get(c));
}
}
}
//輸出指定重復次數的字符串信息
for (String key :map.keySet()){
for (int c:map.get(key).keySet()){
if (c==5||c==6||c==1){
System.out.printf("重復字符串:%s,重復次數:%d,重復字符串出現位置:%s\n",key,c,map.get(key).get(c));
}
}
}
}
public static void main(String[] args) {
String[] arry = {"aa","bb","cc","bb","aa","ooo","dd","aaa","aa"};
// String[] arry = {};
SearchString searchString = new SearchString();
try {
searchString.display(arry);
} catch (Exception e) {
e.printStackTrace();
}
}
}