給定一個(gè)字符串,找到它的第一個(gè)不重復(fù)的字符,并返回它的索引。如果不存在,則返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2
注意事項(xiàng):您可以假定該字符串只包含小寫(xiě)字母。
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
解題思路:
我們要查找第一個(gè)唯一的字符串,怎么才叫唯一呢,只出現(xiàn)一次,那我們就可以找如果出現(xiàn)兩次會(huì)發(fā)生變化的相關(guān)解法
一、使用map,遍歷一遍將其本身和索引下標(biāo)存儲(chǔ),然后再遍歷一遍字符串,看在map里存儲(chǔ)的本身的索引和現(xiàn)在一致么,一致表示是第一個(gè)唯一存在,返回;
//判斷字符串中的第一個(gè)唯一字符---map
class Solution {
public int firstUniqChar(String s) {
Map<Character,Integer> map=new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i),i);
}
for (int i = 0; i < s.length(); i++){
if(map.get(s.charAt(i))== s.indexOf(s.charAt(i))){//說(shuō)明是唯一的 return i;
}
}
return -1;
}
}
空間復(fù)雜度:O(n),
時(shí)間復(fù)雜度:O(n);
解法二: 使用string本身特性,判斷字符的indexof()和lastIndexof();是否相等,相等說(shuō)明一致;
//判斷字符串中的第一個(gè)唯一字符---indexof()
class Solution {
public int firstUniqChar(String s) {
for (int i = 0; i < s.length(); i++) {
char re=s.charAt(i);
if (s.indexOf(re)== s.lastIndexOf(re)){
return i;
}
}
return -1;
}
}
時(shí)間復(fù)雜度:O(n);
空間復(fù)雜度:O(1);
解法二優(yōu)化:只遍歷26個(gè)小寫(xiě)字母,當(dāng)字符串超長(zhǎng)時(shí),減少循環(huán)次數(shù)
class Solution {
public int firstUniqChar(String s) {
int index=-1;
for (char ch = 'a'; ch <= 'z'; ch++) {//只遍歷26哥字母
int beginindex=s.indexOf(ch);
if (beginindex != -1 && beginindex==s.lastIndexOf(ch)){
index=(index == -1 || index>beginindex) ? beginindex :index;
}
}
return index;
}
}
每天一算法,成功有方法。堅(jiān)持
原文鏈接:
https://leetcode-cn.com/problems/first-unique-character-in-a-string/