leetcode-387-easy

First Unique Character in a String

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = "leetcode"
Output: 0
Example 2:

Input: s = "loveleetcode"
Output: 2
Example 3:

Input: s = "aabb"
Output: -1
Constraints:

1 <= s.length <= 105
s consists of only lowercase English letters.

思路一:用长度为 26 的数组存储字符出现过的次数,最后遍历字符串,第一次出现次数为 1 的字符就是求解

    public int firstUniqChar(String s) {
        int[] counts = new int[26];

        for (int i = 0; i < s.length(); i++) {
            counts[s.charAt(i) - 'a']++;
        }

        for (int i = 0; i < s.length(); i++) {
            if (counts[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }

        return -1;
    }
posted @ 2023-01-04 19:19  iyiluo  阅读(16)  评论(0)    收藏  举报