算法 - 从字符串中找到第一个非重复字符

思路:

1. 使用两个存储空间来减少一次循环,将重复的元素放入到set集合,不重复的元素放入List集合。

2. 由于List是有序可重复的数据结构,在循环结束后,存放不重复字符的List中的第一个元素就是我们所要找的第一个非重复字符。

3.  如果在字符串中没有不重复的字符,则返回null或者空字符串。

4. 这种方法一次字符串扫描中找到第一个不重复的字符,时间复杂度是O(n)。

    public static void firstNoRepeatingChar(String str){
        Set<Character> repeat = new HashSet<Character>();
        List<Character> norepeat = new LinkedList<Character>();
        
        try{for (int i=0;i<str.length();i++){
            char c = str.charAt(i);
            if (repeat.contains(c)) continue;
            if (norepeat.contains(c)) {
//                norepeat.remove(norepeat.indexOf(c));
                norepeat.remove((Character)c);
                repeat.add(c);
                System.out.println(repeat);
                System.out.println(norepeat);
            } else {
                norepeat.add(c);
            }
        }
        System.out.println(norepeat.get(0));}
        catch(Exception e){
            System.out.println("all characters are repeating");
        }
    }

 

posted @ 2017-05-04 21:43  测试人生-  阅读(618)  评论(0编辑  收藏  举报