Hash相关 —— 2. 387_字符串中的第一个唯一字符

2. 387_字符串中的第一个唯一字符
import java.util.HashMap;

/**
 *给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
 * Hash o(n)
 */
public class Solution {

    public int firstUniqChar(String s) {
        HashMap<Character, Integer> count = new HashMap<>();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            count.put(c, count.getOrDefault(c, 0) + 1);
        }

        for (int i = 0; i < n; i++) {
            if (count.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
}
/**
 * 利用String方法巧妙解题
 */
class Solution {
    public int firstUniqChar(String s) {
        for(int i=0; i < s.length(); ++i){
            char ch = s.charAt(i);
            if(s.indexOf(ch) == s.lastIndexOf(ch))
                return i;
        }
        return -1;
    }
}
原文地址:https://www.cnblogs.com/s841844054/p/13736255.html