[leetcode]字符串中的第一个唯一字符

起初是想用 o(n) s(n) (扫描一次+hashmap)解决问题的,但是发现不好弄,后来想到用o(n+n) s(n)(扫描两次+hashmap),网上也发现了这种做法,但是感觉这方法有点土,还有更土的就是o(n^2),随便找了个代码提交上去,查看前部分的代码,发现看来这题也不简单,还是有占用时间和空间都小的算法。

    public int firstUniqChar(String s) {
        int result = -1;
        for(char c = 'a';c<='z';c++){
            int index = s.indexOf(c);
            if(index != -1 && index == s.lastIndexOf(c)){
                result = result != -1?Math.min(result,index):index;
            }
        }
        return result;
    }

这段代码很精简,也是个有趣的代码。。。。。对于这种算法不会算时间复杂度。。有时间再去看看

点赞