/**

 * 只允许遍历一遍字符串

 */

public class 找出字符串中第一个只出现一次的字符 {

public static void main(String[] args) {

// 测试字符串

String str = "asdsacjj";

// 字符串转化成字符

char[] strToChar = str.toCharArray();

int len = strToChar.length;//字符串长度

//hashset用于判断是否出现过

HashSet<Character> hashset = new HashSet<Character>();

//hashIndex记录只出现一次的字符的第一个位置

HashMap<Character, Integer> hashIndex = new HashMap<Character, Integer>();

/**

* 先判断是否曾经出现

* 没有就记录在hashIndex

* 有则删除hashIndex已经保存的信息

*/

for (int i = 0; i < len ; i++) {

if(!hashset.contains(strToChar[i])){

hashset.add(strToChar[i]);

hashIndex.put(strToChar[i], i);

}else{

if(hashIndex.containsKey(strToChar[i])){

hashIndex.remove(strToChar[i]);

}

}

}

/**

* 转化成ist,用Collections.sort的Comparator去比较

* 容器的内部排序要注意

*/

  List<Map.Entry<Character, Integer>> dataList= new ArrayList<Map.Entry<Character,Integer>>(hashIndex.entrySet());

  Collections.sort(dataList,new Comparator<Map.Entry<Character,Integer>>() {

@Override

public int compare(Map.Entry<Character, Integer> o1,

Entry<Character, Integer> o2) {

if(o1.getValue().compareTo(o2.getValue())>0){

return 1;

}

// TODO Auto-generated method stub

return -1;

}   

});

System.out.println(dataList.get(0));

}

}