美文网首页
First Unique Character in a Stri

First Unique Character in a Stri

作者: nafoahnaw | 来源:发表于2018-03-14 17:49 被阅读0次

    Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

    Examples:

    s = "leetcode"
    return 0.

    s = "loveleetcode",
    return 2.
    Note: You may assume the string contain only lowercase letters.

    找出给定小写字符串中最早出现的不重复字符

       public int firstUniqChar(String s) {
            /**
             * 只有26个字母,所以初始化一个长度26的数组
             */
            int[] freq = new int[26];
            for(int i = 0 ; i< s.length();i++){
                //循环给出的字符串字符,将其相应的数组下标元素+1
                //那么该数组中元素=1的下标就是所有不重复的字符
                freq[s.charAt(i) - 'a'] ++ ;
            }
            //找到所有不重复的字符之后,接下就是找出s中第一个出现的不重复字符
            //再次循环s字符串字符判断第一个元素=1的下标就是结果
            for(int i = 0; i< s.length();i++){
                if(freq[s.charAt(i) - 'a'] == 1){
                    return i;
                }
            }
            return -1;
        }
    

    相关文章

      网友评论

          本文标题:First Unique Character in a Stri

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