华中科技大学 找位置(java)

题目描述
对给定的一个字符串,找出有重复的字符,并给出其位置,如:abcaaAB12ab12 输出:a,1;a,4;a,5;a,10,b,2;b,11,1,8;1,12, 2,9;2,13。
输入描述:
输入包括一个由字母和数字组成的字符串,其长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据,
按照样例输出的格式将字符出现的位置标出。

1、下标从0开始。
2、相同的字母在一行表示出其出现过的位置。
示例1
输入
复制
abcaaAB12ab12
输出
复制
a:0,a:3,a:4,a:9
b:1,b:10
1:7,1:11
2:8,2:12
import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
    public static void main(String[] args){   	
    	try {
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		String str;
    		while((str=br.readLine()) != null) {
    			char[] ch = str.toCharArray();
    			ArrayList<ArrayList<String>> res = new ArrayList<>();
    			HashMap<Character, Integer> map = new HashMap<>();
    			int count = 0;
    			for(int i = 0; i < ch.length; i++) {
    				if(map.containsKey(ch[i])) {
    					res.get(map.get(ch[i])).add(ch[i]+":"+i); 
    				}
    				else {
    					ArrayList<String> tmp = new ArrayList<>();
    					tmp.add(ch[i]+":"+i);
    					res.add(tmp);
    					map.put(ch[i], count);
    					count++;
    				}
    			} 
    			for(int i = 0; i < res.size(); i++) {
    				ArrayList<String> tmp = res.get(i);
    				if(tmp.size() == 1) continue;
    				System.out.print(tmp.get(0));    				
    				for(int j = 1; j < tmp.size(); j++) {
    					System.out.print(","+tmp.get(j));
    				}
    				System.out.println();
    			}
    		}
    	} catch(IOException e){
    		e.printStackTrace();
    	}
    }
}



发布了231 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104225137