Java实现:在字符串中找到第一个不重复的字符

public static char getFirstNoRepeatChar(String str) { 

        // 使用LinkedHashMap可以记住元素的插入顺序 

       Map<Character, Integer> map = new LinkedHashMap<Character,Integer>( 

               str.length()); 

        for (char c :str.toCharArray()) { 

            // 以字符作为k 出现的个数作为值 

            map.put(c,map.containsKey(c) ? map.get(c) + 1 : 1); 

        } 

        // 遍历Map 找到第一个值为1的就是找的结果 

        for(Entry<Character, Integer> entry : map.entrySet()) { 

            if(entry.getValue() == 1) 

                returnentry.getKey(); 

        } 

        throw newRuntimeException("没有找到相关的字符"); 

    }  

猜你喜欢

转载自blog.csdn.net/isduxd/article/details/78997151