美文网首页
LeedCode 字符串中的第一个唯一字符

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

作者: 红枣枸杞OP | 来源:发表于2018-07-11 14:23 被阅读0次

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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<Character, Integer> datas = new HashMap<Character, Integer>();
            
            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<c.length;j++)
                {
                    if(key == c[j]&&j<result)
                    {
                        result = j;
                    }
                }
                     System.out.println(key);
                     continue;
                 }
            }
            if(result == c.length)
            {
                return -1;    
            }
             return result;   
            }
        }
    

    思路二
    用桶排序的思路,用长度为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<s.length();i++)
           {
               que[s.charAt(i)-'a']++;
           }//计算每个字符出现的次数
            for(int i=0;i<s.length();i++)
            {
                if(que[s.charAt(i)-'a']==1)
                {
                    return i;
                    
                }
                
            }
            return -1;
            }
        }
    

    相关文章

      网友评论

          本文标题:LeedCode 字符串中的第一个唯一字符

          本文链接:https://www.haomeiwen.com/subject/inxhpftx.html