zoukankan      html  css  js  c++  java
  • 算法

    思路:

    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");
            }
        }
  • 相关阅读:
    RegExp实例
    Date类型之组件方法
    Date类型之继承方法
    数组常见方法下
    Math对象
    数组常见方法上
    CSS变量
    基本类型和引用类型
    Python习题集(十五)
    Python习题集(十四)
  • 原文地址:https://www.cnblogs.com/clarke157/p/6810043.html
Copyright © 2011-2022 走看看