1. 程式人生 > >387. First Unique Character in a String(python+cpp)

387. First Unique Character in a String(python+cpp)

題目:

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。第一反應是遍歷字串,暴力count。 python程式碼:

from collections import Counter
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        _dict=Counter(s)
        for i in xrange(len(s)):
            if _dict[s[i]]==1:
                return i  
        return -1

python中,有find()

rfind()(返回字串最後一次出現的位置),如果字串中某個字母只出現過一次,那麼find()的結果與rfind()的結果一樣,前提是要先把字母表打出來,這樣速度更快。 python程式碼:

from collections import Counter
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        alphas="qwertyuiopasdfghjklzxcvbnm";
        min_index=
len(s) for letter in alphas: index1=s.find(letter) index2=s.rfind(letter) if index1!=-1 and index1==index2: min_index=min(min_index,index1) return min_index if min_index!=len(s) else -1

c++程式碼:

class Solution {
public:
    int firstUniqChar(string s) {
        string alphas="qwertyuiopasdfghjklzxcvbnm";
        unsigned long int min_index=s.size();
        for (auto letter:alphas)
        {   auto index1=s.find(letter);
            auto index2=s.rfind(letter);
            //cout<<letter<<" "<<index1<<" "<<index2<<endl;
            if (index1!=string::npos && index1==index2)
            {
                
                min_index=min(min_index,index1);
                //cout<<letter<<" "<<min_index<<endl;
                
            }
                
        }
        return min_index==s.size()?-1:min_index;
    }
};

總結: string find()系列函式,返回型別是size_type 實際上是unsigned long int,注意不是int,也注意不要把size_type 強制轉換為int