1. 程式人生 > >LeetCode-First Unique Character in a String

LeetCode-First Unique Character in a String

Description: 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.

題意:給定一個字串,返回字串中第一個在字串中只出現過一次的字元的下標位置,沒有找到就返回-1;

解法:我們可以利用雜湊表,遍歷字串,將字元及其出現的次數作為鍵值對儲存在表中;之後,再從首部開始遍歷字串,返回對應鍵的值1的那個字元的下標位置;

Java
class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> table = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            table.put(s.charAt(i), table.getOrDefault(s.charAt(i), 0) + 1);
        }
        for (int i = 0; i < s.length(); i++) {
            if (table.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
}