387. First Unique Character in a String

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.

难度: easy

题目:给定字符串,找出第一个不重复的字符,并返回其下标。如果不存在则返回-1.

思路:数组分别记录下标与出现次数。

Runtime: 10 ms, faster than 93.94% of Java online submissions for First Unique Character in a String.
Memory Usage: 40 MB, less than 14.74% of Java online submissions for First Unique Character in a String.

class Solution {
    public int firstUniqChar(String s) {
        int[] count = new int[26];
        int[] index = new int[26];
        int result = s.length();
        for (int i = 0; i < result; i++) {
            char c = s.charAt(i);
            count[c - 'a']++;
            index[c - 'a'] = i + 1;
        }
        
        for (int i = 0; i < 26; i++) {
            if (1 == count[i]) {
                result = Math.min(result, index[i] - 1);
            }
        }
        
        return result >= s.length() ? -1 : result;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018386796
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞