1. 程式人生 > >[LeetCode] 387. First Unique Character in a String 字符串的第一個唯一字符

[LeetCode] 387. First Unique Character in a String 字符串的第一個唯一字符

.get 分配 找到 xrange discard obj ase 統計 返回

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個字母,所以可以用數組來統計出現的個數。

Java: Brute Force

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:

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:

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:

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:  

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:

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

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

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

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])  

C++:

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;
    }
};

  

[LeetCode] 387. First Unique Character in a String 字符串的第一個唯一字符