Python教程——字符串中的第一個(gè)唯一字符
題目:
給定一個(gè)字符串,找到它的第一個(gè)不重復(fù)的字符,并返回它的索引。如果不存在,則返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事項(xiàng):您可以假定該字符串只包含小寫字母。
解題思路:
很簡單的題,無非就是對(duì)字符串的字母進(jìn)行頻率統(tǒng)計(jì),找到出現(xiàn)頻率為1 的字母索引。
借助哈希映射兩次遍歷完成。第一次遍歷進(jìn)行字母頻率統(tǒng)計(jì),Hash Map 的Key 為字母,Value 為出現(xiàn)頻率。第二次遍歷找到頻率為 1 的字母索引返回即可。
不同于單詞頻率統(tǒng)計(jì),字母一共只有 26 個(gè),所以可以直接利用 ASii 碼表里小寫字母數(shù)值從 97~122,直接用 int 型數(shù)組映射。建立映射:索引為 小寫字母的 ASii 碼值,存儲(chǔ)值為出現(xiàn)頻率。
哈希映射解題:
Java:
class Solution {
public int firstUniqChar(String s) {
char[] chars = s.toCharArray();//轉(zhuǎn)成 Char 數(shù)組
Map map = new HashMap<>();
for (Character c: chars) map.put(c, map.getOrDefault(c, 0) + 1);//頻率統(tǒng)計(jì)
for (int i = 0; i < chars.length; i++) {
if(map.get(chars[i])==1) return i;//找到詞頻為1的字母(只出現(xiàn)一次)返回其索引
}
return -1;
}
}
Python:
class Solution:
def firstUniqChar(self, s):
count = collections.Counter(s)# 該函數(shù)就是Python基礎(chǔ)庫里詞頻統(tǒng)計(jì)的集成函數(shù)
index = 0
for ch in s:
if count[ch] == 1:
return index
else:
index += 1
return -1
數(shù)組映射解題:
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 基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)里沒有 char 型,強(qiáng)行使用chr(i)轉(zhuǎn)換,只會(huì)導(dǎo)致效率更低
字符串函數(shù)解題:
Java:
利用 Java 字符串集成操作函數(shù)解題,很巧妙,效率也很高。
其中:
indexOf(): 返回該元素第一次出現(xiàn)的索引,沒有則返回 -1
lastIndex(): 返回該元素最后一次出現(xiàn)的索引,沒有則返回 -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) {//兩次索引值相同則證明該字母只出現(xiàn)一次
res = Math.min(firstIndex, res);//res 為只出現(xiàn)一次的字母中索引值最小的
}
}
return res == s.length() ? -1 : res;
}
}
大家有什么意見的或者建議歡迎留言指出!更多的Python教程也會(huì)繼續(xù)為大家更新!大家有需要學(xué)習(xí)課程的也可以岫巖或者私信!


