387. 字符串中的第一个唯一字符(简单题)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43105156/article/details/102153113

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

案例:

s = “leetcode”
返回 0.

s = “loveleetcode”,
返回 2.

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

class Solution {
    public int firstUniqChar(String s) {
        if (s == "") return -1;
        int[] count = new int[26];
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            count[ch[i] - 'a']++;
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < count.length; i++) {
            if(count[i] == 1) min = Math.min(min,s.indexOf((char)(i+'a')));
        }
        return min==Integer.MAX_VALUE ? -1 : min ;
    }
}

简便算法,来源题解:

class Solution {
    public int firstUniqChar(String s) {
        int index = Integer.MAX_VALUE;
        for (char ch = 'a'; ch <= 'z'; ch++) {
            int beginIndex = s.indexOf(ch);
            if (beginIndex != -1 && beginIndex == s.lastIndexOf(ch)) {
                index = Math.min(index,beginIndex);
            }
        }
        return index == Integer.MAX_VALUE? -1 : index;
    }
}

思路概述:
从a遍历到z,若该字母只出现一次,代表其在字符串中调用indexOf()方法和调用lastIndextOf()方法的结果一致。此时令index记录较小的值。

猜你喜欢

转载自blog.csdn.net/weixin_43105156/article/details/102153113