[LeetCode] 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.

给一个字符串,找出第一个不重复的字符,返回它的index,如果不存在,返回-1。假设字符都是小写字母。

解法1: 暴力搜索, T:O(n^2)

解法2: HashMap,第一次遍历每一个字符,统计每种字符出现的次数。第二次遍历,找到第一出现的字符次数为1的字符。

解法3: int [26]数组,由于只有26个字母,所以可以用数组来统计出现的个数。

解法4: 循环26个字母,统计每个字母出现次数为1的字母,写入按出现的index排序的数组。然后取数组里最前面的那个或者为空时是-1

Java: Brute Force

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
    public static int firstUniqChar(String s){
        for (int i = 0; i < s.length(); i++) {
            boolean isUnique = true;
            for (int j = 0; j < s.length(); j++) {
                if (i != j && s.charAt(i) == s.charAt(j)){
                    isUnique = false;
                    break;
                }
            }
            if (isUnique) return i;
        }
        return -1;
    }
}  

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int firstUniqChar(String s){
        Map<Character, Integer> charMap = new HashMap<>(s.length()); //预先分配大小,避免扩容性能影响
        for (int i = 0; i < s.length(); i++) {
            if (!charMap.containsKey(s.charAt(i))){
                charMap.put(s.charAt(i), 1);
            }else {
                charMap.put(s.charAt(i), charMap.get(s.charAt(i))+1);
            }
        }
 
        for (int i = 0; i < s.length(); i++) {
            if (charMap.get(s.charAt(i)) == 1){
                return i;
            }
        }
        return -1;
    }
}  

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution { 
    public int firstUniqChar(String s) { 
        char[] array = s.toCharArray(); 
        int[] a = new int[26]; 
        for(int i=0;i<s.length();i++)a[array[i]-'a']++; 
        for(int i=0;i<s.length();i++){ 
            if(a[array[i]-'a']==1){ 
                return i; 
            
        
        return -1
    
}

Java:

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int firstUniqChar(string s) { 
        vector<int> count(26); 
        for(int i=0;i<s.size();i++) 
            count[s[i]-'a']++; 
        for(int i=0;i<s.size();i++) 
            if(count[s[i]-'a']==1
                return i; 
        return -1
    
}

Java:  

1
2
3
4
5
6
7
8
class Solution {
    public int firstUniqChar(String s) { 
      for(int i = 0; i<s.length(); i++) { 
        if(s.lastIndexOf(s.charAt(i))==s.indexOf(s.charAt(i))) return i; 
       
       return -1
    
}  

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        letters = {}
        for c in s:
            if c in letters:
                letters[c] = letters[c] + 1
            else:
                letters[c] = 1   
        for i in xrange(len(s)):
            if letters[s[i]] == 1:
                return i
        return -1  

Python: 162ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from collections import defaultdict
 
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        lookup = defaultdict(int)
        candidtates = set()
        for i, c in enumerate(s):
            if lookup[c]:
                candidtates.discard(lookup[c])
            else:
                lookup[c] = i+1
                candidtates.add(i+1)
 
        return min(candidtates)-1 if candidtates else -1

Python: 92ms

1
2
3
4
5
6
7
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        return min([s.find(c) for c in 'abcdefghijklmnopqrstuvwxyz' if s.count(c)==1] or [-1])

Python: 75ms

1
2
3
4
5
6
7
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        return min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1])  

Python: 60ms

1
2
3
4
5
6
7
8
9
def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
         
        letters='abcdefghijklmnopqrstuvwxyz'
        index=[s.index(l) for l in letters if s.count(l) == 1]
        return min(index) if len(index) > 0 else -1 

C++:

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, int> m;
        for (char c : s) ++m[c];
        for (int i = 0; i < s.size(); ++i) {
            if (m[s[i]] == 1) return i;
        }
        return -1;
    }
};

  

All LeetCode Questions List 题目汇总

 

posted @   轻风舞动  阅读(2207)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示