第一个只出现一次的字符

来源:互联网 发布:徐老师杂货铺 淘宝 编辑:程序博客网 时间:2024/05/16 01:14

题目描述
在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符,并返回它的位置

算法
很显然,我们可以想到利用映射关系来解决,我们这里渴望字符可以和它出现的次数产生一个映射关系,所以我们这里可以将字符作为key,次数作为value值,来产生一个简化哈希表,所以我们需要扫描字符串两次,第一次统计字符,第二次找出第一个符合条件的字符。

代码如下:

    public int FirstNotRepeatingChar(String str) {        if (str == null || str.length() < 0) {            return -1;        } else if (str.length() == 1) {            return 0;        }        int[] table = new int[256];        for (int i = 0; i < str.length(); i++) {            table[str.charAt(i)] ++;        }        for (int i = 0; i < str.length(); i++) {            if (table[str.charAt(i)] == 1){               return i;            }        }        return -1;    }
0 0
原创粉丝点击