387. 字符串中的第一个唯一字符

哈希表

class Solution {
    public int firstUniqChar(String s) {
        int[] arr = new int[26];

        /**
         * 先将所有字母的词频保存下来
         */
        for (int i = 0; i < s.length(); i++) {
            arr[s.charAt(i) - 'a']++;
        }

        /**
         * 然后挨个进行判断是否等于1
         */
        for (int i = 0; i < s.length(); i++){

            if (arr[s.charAt(i) - 'a'] == 1){
                return i;
            }
        }

        return -1;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/first-unique-character-in-a-string/

posted @ 2021-11-18 21:44  振袖秋枫问红叶  阅读(32)  评论(0)    收藏  举报