LeedCode 字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例

返回 0.
s = "loveleetcode",
返回 2

思路一
将每个字符出现的次数用HashMap存储起来,key为字符,value为次数,然后找到最先出现的不重复字符。时间复杂度O(N^2)

class Solution {
    public int firstUniqChar(String s) {
        if(s.length()==0)
        {
            return -1;
        }
        if(s.length()==1)
        {
            return 0;
        }
        char []c;
        c = s.toCharArray();
        int result=c.length;
        
        HashMap datas = new HashMap();
        
        for (char i:c) {
             
            Character key = i;
            Integer value = datas.get(key);
            if (value==null) {
                datas.put(key, 1);
            }else{
                datas.put(key, value+1);
            }
        }
        for(Character key:datas.keySet())
        {
             if(datas.get(key)== 1)
             {
                
                 for(int j=0;j

思路二
用桶排序的思路,用长度为26的数组对每个字符出现的次数进行统计。比HashMap少了一个嵌套查询的步骤,时间复杂度O(n)

    public int firstUniqChar(String s) {
        if(s.length()==0)
        {
            return -1;
        }
        if(s.length()==1)
        {
            return 0;
        }
        char []c;
        int []que = new int[26]; 
        c = s.toCharArray();
       for(int i=0;i

你可能感兴趣的:(LeedCode 字符串中的第一个唯一字符)