Skip to content

Latest commit

 

History

History
145 lines (113 loc) · 2.83 KB

File metadata and controls

145 lines (113 loc) · 2.83 KB

English Version

题目描述

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

 

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

 

提示:你可以假定该字符串只包含小写字母。

解法

遍历字符串,用一个 map 或者字典存放字符串中每个字符出现的次数。然后再次遍历字符串,取出对应字符出现的次数,若次数为 1,直接返回当前字符串的下标。遍历结束,返回 -1。

Python3

class Solution:
    def firstUniqChar(self, s: str) -> int:
        counter = Counter(s)
        for i, c in enumerate(s):
            if counter[c] == 1:
                return i
        return -1

Java

class Solution {
    public int firstUniqChar(String s) {
        int[] counter = new int[26];
        for (char c : s.toCharArray()) {
            ++counter[c - 'a'];
        }
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (counter[c - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}

TypeScript

function firstUniqChar(s: string): number {
    let record = new Map();
    for (let cur of [...s]) {
        record.set(cur, record.has(cur));
    }
    for (let i = 0; i < s.length; i++) {
        if (!record.get(s[i])) return i;
    }
    return -1;
}

C++

class Solution {
public:
    int firstUniqChar(string s) {
        vector<int> counter(26);
        for (char& c : s) ++counter[c - 'a'];
        for (int i = 0; i < s.size(); ++i)
            if (counter[s[i] - 'a'] == 1)
                return i;
        return -1;
    }
};

Go

func firstUniqChar(s string) int {
	counter := make([]int, 26)
	for _, c := range s {
		counter[c-'a']++
	}
	for i, c := range s {
		if counter[c-'a'] == 1 {
			return i
		}
	}
	return -1
}

JavaScript

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function (s) {
    const counter = new Map();
    for (let c of s) {
        counter[c] = (counter[c] || 0) + 1;
    }
    for (let i = 0; i < s.length; ++i) {
        if (counter[s[i]] == 1) {
            return i;
        }
    }
    return -1;
};

...