1. 程式人生 > >【leetcode】字串中的第一個唯一字元(C、Python解答)

【leetcode】字串中的第一個唯一字元(C、Python解答)

題目:

字串中的第一個唯一字元

給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事項:您可以假定該字串只包含小寫字母。

C解答:

在迴圈中設定標誌位來記錄此字母是否有重複

int firstUniqChar(char* s) {
    int k,i,j;
    int len=strlen(s);
    if(len==1)//特殊情況優先考慮
        return 0;
    if(len==0)
        return -1;
    k=0;//標誌s[i]是不是唯一字元
    for(i=0;i<len;i++)
    {
        k=0;//每次都初始化
        for(j=0;j<len;j++)
            if(s[i]==s[j]&&i!=j)
            {
                k=1;
                break;
            }
        if(k==0)//s[i]是唯一字元且是第一個
            return i;
    }
    return -1;
}

Python解答:

使用Python內建模組collections的Count函式

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic=collections.Counter(s)
        for i in range(0,len(s)):
            if dic[s[i]]<2:
                return i
        return -1

今天才發現Leetcode可以看別人提交的優秀程式碼!以前不知道,真的很遺憾,以後儘量在部落格中改進自己的演算法吧!

把更多的精力發在提高程式效率上,而非功能實現上!