每天一道LeetCode Day15:字符串中第一个唯一字符出现的位置

题目

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

示例:
s = “leetcode”
返回 0

s = “loveleetcode”
返回 2

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 分析
    建立一个数组int count[] 统计每一个字符出现的次数。
    按照字符串s 的顺序遍历count[],如果出现是1,则返回当前的字符所对应的位置即可。
    public int firstUniqChar(String s) {
        int[] count=new int[256];
        for(int i=0;i<s.length();i++){
            char ch=s.charAt(i);
            count[ch]++;
        }

        for(int i=0;i<s.length();i++){
            char ch=s.charAt(i);
            if(count[ch]==1){
                return i;
            }
        }
        return -1;
    }

在这里插入图片描述


版权声明:本文为u014141841原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。