leetcode修炼之路——387. First Unique Character in a String

最近公司搬家了,有两天没写了,今天闲下来了,继续开始算法之路。

leetcode的题目如下:

 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

 

Note: You may assume the string contain only lowercase letters. 

 

题目分析:

题目总体来说还是比较easy,就是查找第一个不重复的字符的位置,如果没有的话,返回-1.

代码实现:

public static int firstUniqChar(String s) {

        List<Integer> list = new ArrayList<>();//记录已经重复的位置

        if (s.length() == 1) {
            return 0;
        }

        for (int i = 0; i < s.length(); i++) {

            if (!list.contains(i) && i == s.length() - 1) {//最后一个且不在重复列表中
                return i;
            }

            if (list.contains(i)) {//判断是否为重复的位置
                continue;
            } else {
                for (int j = i + 1; j < s.length(); j++) {
                    if (s.charAt(i) == s.charAt(j)) {

                        if (!list.contains(i)) {//把当前的也add进去,最后会判断
                            list.add(i);
                        }

                        list.add(j);//把重复的位置add进去
                    }

                    if (j == s.length() - 1 && !list.contains(i)) {//最终判断条件
                        return i;
                    }
                }
            }

        }

        return -1;
    }

上述方法在测试中没有发现问题,但是在效率上出现了比较大的问题,因为 list.contains(i)这是一个循环实现,这使得时间复杂度增加,因此,下面进行了优化:

public static int firstUniqChar2(String s) {

        int[] count = new int[26];//最多26个字符

        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;//记录每个字符出现的次数
        }

        for (int i = 0; i < s.length(); i++) {
            if (count[s.charAt(i) - 'a'] == 1) {//判断当前出现的字符是否值出现了一次
                return i;
            }
        }

        return -1;
    }

这个方法在前几个算法中都出现了,这次在第一个算法出现了算法的执行时间超时的问题后就想到用这种方式来实现。(ps:在最后判断的时候脑子抽了,没有想到结果判断条件,最后还是查了下才恍然大明白mdzz)。

^_^

posted @ 2016-08-23 22:04  风起云涌,勿忘本心  阅读(267)  评论(0编辑  收藏  举报