第一个只出现一次的字符位置

在一个字符串中找到第一个只出现一次的字符,并返回它的位置。java

Input: abacc
Output: b

 

解题思路:数组

最直观的解法是使用 HashMap 对出现次数进行统计,可是考虑到要统计的字符范围有限,所以能够使用整型数组代替 HashMap,从而将空间复杂度由 O(N) 下降为 O(1)。code

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        int[] cnts = new int[256];  //建立数组
        for(int i =0;i<str.length();i++)   //遍历
            cnts[str.charAt(i)]++;
        for(int i =0;i<str.length();i++)
            if(cnts[str.charAt(i)] == 1)
                return i;
        return -1;
    }
}
相关文章
相关标签/搜索