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.

Note: You may assume the string contain only lowercase letters.

class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> map = new LinkedHashMap();
        int res = 0;
        int le = s.length();
        if(le == 0) return -1;
        for(int i = 0; i < le; i++){
            char c = s.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for(Map.Entry<Character, Integer> entry: map.entrySet()){
            char c = entry.getKey();
            int tmp = entry.getValue();
            if(tmp == 1){
                res = s.indexOf(c);
                return res;
                
            }
        }
        return -1;
    }
}

LinkedHashMap,能有序的存放数据。

class Solution {
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> count = new HashMap<Character, Integer>();
        int n = s.length();
        // build hash map : character and how often it appears
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            count.put(c, count.getOrDefault(c, 0) + 1);
        }
        
        // find the index
        for (int i = 0; i < n; i++) {
            if (count.get(s.charAt(i)) == 1) 
                return i;
        }
        return -1;
    }
}

简化版,按字母顺序遍历也可以。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11856716.html