import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Scanner; /** * 对给定的一个字符串,找出有重复的字符,并给出其位置, 如:abcaaAB12ab12 * 输出:a,1;a,4;a,5;a,10,b,2;b,11,1,8;1,12, 2,9;2,13 * * :这种找位置的使用map一一对应 * 虽然实现这部分代码,但是却没有想出解决顺序的方案 * @author kif * */ public class FindSeat { public static void findSeat(String str) { LinkedHashMap<Character, StringBuffer> map = new LinkedHashMap<Character, StringBuffer>(); for(int i = 0 ; i < str.length() ; i++){ Character ch = str.charAt(i); if(map.containsKey(ch)){ StringBuffer strbuf = map.get(ch); map.remove(ch); strbuf.append(":"+i); map.put(ch, strbuf); }else{ map.put(ch, new StringBuffer(i+"")); } } Iterator iter = map.keySet().iterator(); while(iter.hasNext()){ Object obj = iter.next(); //获取每个键相对应的值 String strs = map.get((Character)obj).toString(); // System.out.println(strs); String st[] = strs.split(":"); for(String s : st){ System.out.print(obj+"-"+s+","); } System.out.println(); } } public static void main(String[] args) { Scanner input = new Scanner(System.in); String str = input.nextLine(); FindSeat.findSeat(str); input.close(); } }
时间: 2024-10-11 00:59:43