zoukankan      html  css  js  c++  java
  • 求仅出现一次的最早字符

    题目

    请实现一个函数用来找出字符流中第一个只出现一次的字符。

    例如输入google,输出l

    代码

     1     private static Set<Character> filter = new HashSet<>();
     2     private static LinkedList<Character> result = new LinkedList<>();
     3 
     4     private static void getFirstChar(String string) {
     5         char[] chars = string.toCharArray();
     6         for (Character ch : chars) {
     7             if (!filter.contains(ch)) {
     8                 int cIndex = result.indexOf(ch);//避免使用contains底层遍历多次
     9                 if (cIndex == -1) {
    10                     result.add(ch);
    11                 } else {
    12                     result.remove(cIndex);//复用
    13                     filter.add(ch);
    14                 }
    15             }
    16         }
    17         System.out.println(result.size() == 0 ? "#" : result.getFirst());
    18     }

    上述是我写的代码,后来发现一个学弟写的更好,来贴一下,大家围观~~

     1     public static void findChar(String string) {
     2         char[] chars = new char[256];//所有字符--256,同时此处用char不用Int是为了减少空间
     3         for (int i = 0; i < string.length(); i++) {
     4             chars[string.charAt(i)]++;
     5         }
     6         for (int i = 0; i < string.length(); i++) {
     7             if (chars[string.charAt(i)] == 1) {
     8                 System.out.println(string.charAt(i));
     9                 break;
    10             }
    11             if (chars[string.charAt(i)] != 1 && i == string.length() - 1) {
    12                 System.out.println("#");
    13             }
    14         }
    15     }
  • 相关阅读:
    Java入门——(3)面对对象(下)
    Java入门——(8)网络编程
    Java入门——(2)面对对象(上)
    MAC下的Intellij IDEA常用快捷键
    RedHat安装yum+配置国内yum源
    XGBoost算法
    Bagging和Boosting 概念及区别
    关于python的sort和sorted
    sklearn中常用数据预处理方法
    安装Scala
  • 原文地址:https://www.cnblogs.com/sachen/p/7102499.html
Copyright © 2011-2022 走看看