码迷,mamicode.com
首页 > 编程语言 > 详细

字符串中第一个只出现一次的字符,如何优化算法使得遍历次数更少?

时间:2014-10-15 04:55:00      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:字符串中第一个只出现一次的字符   如何优化算法使得遍历次数更少?   

/**

 * 只允许遍历一遍字符串

 */

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));

}

}


本文出自 “DamenMai学习之路” 博客,转载请与作者联系!

字符串中第一个只出现一次的字符,如何优化算法使得遍历次数更少?

标签:字符串中第一个只出现一次的字符   如何优化算法使得遍历次数更少?   

原文地址:http://9492221.blog.51cto.com/9482221/1564119

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!