东寻

导航

第一个只出现一次的字符

##题目描述 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

思路

桶计数。
时间复杂度O(n),空间复杂度O(1)。

代码

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str == null || str.length() == 0)    return -1;
        int[] map = new int[256];
        for(int i = 0; i < str.length(); i++) {
            map[str.charAt(i)]++;
        }
        for(int i = 0; i < str.length(); i++) {
            if(map[str.charAt(i)] == 1) {
                return i;
            }
        }
        return -1;
    }
}

posted on 2020-02-24 14:17  东寻  阅读(127)  评论(0编辑  收藏  举报