1. 程式人生 > 其它 >Leetcode387. 字串中的第一個唯一字元

Leetcode387. 字串中的第一個唯一字元

技術標籤:LeetCode

Leetcode387. 字串中的第一個唯一字元

class Solution {
    public int firstUniqChar(String s) {
        if (s == null || "".equals(s.trim())) {
            return -1;
        }
        // 開闢一個數組,記錄每個字元出現的次數
        int[] array = new int[26];
        int length = s.length();
        for (
int i = 0; i < length; i++) { array[s.charAt(i) - 'a']++; } // 再次遍歷字串,找到只出現一次的字元 for (int i = 0; i < length; i++) { if (array[s.charAt(i) - 'a'] == 1) { return i; } } return -1; } }