387: a unique string of first character

Problem Description

Given a string, find its first non-repeating characters, and returns its index. If not, it returns -1.

Examples

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

Note: You can assume that the string contains only lowercase letters.

Thinking

Maintaining the contents of the string into a hashMap, the counting of the number of occurrences.
Then traverse the string, the first count of the subscript 1 in the return to the hashMap.

AC Code

class Solution {
    public int firstUniqChar(String s) {
        int[] arr = new int[26];
        char[] chars = s.toCharArray();
        for(char c:chars){
            arr[c-'a']++;
        }
        for(int i = 0; i < chars.length; i++){
            if(arr[chars[i]-'a'] == 1){
                return i;
            }
        }
        return -1;
    }
}
Published 396 original articles · won praise 22 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_41687289/article/details/104914800