Python教程:字符串中的第一個唯一字符

Python教程——字符串中的第一個唯一字符

題目:

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

案例:

s = "leetcode"

返回 0.

s = "loveleetcode",

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

解題思路:

​ 很簡單的題,無非就是對字符串的字母進行頻率統計,找到出現頻率爲1 的字母索引。

​ 藉助哈希映射兩次遍歷完成。第一次遍歷進行字母頻率統計,Hash Map 的Key 爲字母,Value 爲出現頻率。第二次遍歷找到頻率爲 1 的字母索引返回即可。

​ 不同於單詞頻率統計,字母一共只有 26 個,所以可以直接利用 ASii 碼錶裏小寫字母數值從 97~122,直接用 int 型數組映射。建立映射:索引爲 小寫字母的 ASii 碼值,存儲值爲出現頻率。

哈希映射解題:

Java:

class Solution {

public int firstUniqChar(String s) {

char[] chars = s.toCharArray();//轉成 Char 數組

Map map = new HashMap<>();

for (Character c: chars) map.put(c, map.getOrDefault(c, 0) + 1);//頻率統計

for (int i = 0; i < chars.length; i++) {

if(map.get(chars[i])==1) return i;//找到詞頻爲1的字母(只出現一次)返回其索引

}

return -1;

}

}
Python:

class Solution:

def firstUniqChar(self, s):

count = collections.Counter(s)# 該函數就是Python基礎庫裏詞頻統計的集成函數

index = 0

for ch in s:

if count[ch] == 1:

return index

else:

index += 1

return -1
數組映射解題:

Java:

class Solution {

public int firstUniqChar(String s) {

char[] chars = s.toCharArray();

int base = 97;

int[] loc = new int[26];

for (char c:chars) loc[c - base] += 1;

for (int i = 0; i < chars.length; i++) {

if(loc[chars[i]-base]==1) return i;

}

return -1;

}

}
Python 基礎數據結構裏沒有 char 型,強行使用chr(i)轉換,只會導致效率更低

Python教程:字符串中的第一個唯一字符
字符串函數解題:

Java:

利用 Java 字符串集成操作函數解題,很巧妙,效率也很高。

其中:

indexOf(): 返回該元素第一次出現的索引,沒有則返回 -1

lastIndex(): 返回該元素最後一次出現的索引,沒有則返回 -1

class Solution {

public int firstUniqChar(String s) {

int res = s.length();

for (int i = 'a'; i <= 'z'; i++) {

int firstIndex = s.indexOf((char)i);

if (firstIndex == -1) continue;

int lastIndex = s.lastIndexOf((char)i);

if (firstIndex == lastIndex) {//兩次索引值相同則證明該字母只出現一次

res = Math.min(firstIndex, res);//res 爲只出現一次的字母中索引值最小的

}

}

return res == s.length() ? -1 : res;

}

}
大家有什麼意見的或者建議歡迎留言指出!更多的Python教程也會繼續爲大家更新!大家有需要學習課程的也可以岫巖或者私信!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章