跳转至

387. First Unique Character in a String

LeetCode Hash Table String

Given a string, find the first non-repeating character in it and return its 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.

分析

使用哈希表存储每个字符出现的次数。遍历字符串,找到第一个仅出现一次的字符的位置。

public int firstUniqChar(String s) {
    if (s == null || s.length() == 0) return -1;
    int[] map = new int[128];
    char[] cs = s.toCharArray();
    for (char c : cs) map[c]++;
    for (int i = 0; i < cs.length; i++)
        if (map[cs[i]] == 1) return i;
    return -1;
}