每日一題20.12.23 387. 字串中的第一個唯一字元 java題解
阿新 • • 發佈:2020-12-25
題目
https://leetcode-cn.com/problems/first-unique-character-in-a-string/
方法一:計數
兩次遍歷
class Solution {
public int firstUniqChar(String s) {
if(s==null||s.length()==0)
return -1;
int len=s.length();
int[] count=new int[26];
for (int i=0;i<len;i++){
count[s.charAt(i)-'a']++;
}
for(int i=0;i<len;i++){
char c=(Character)s.charAt(i);
if(count[c-'a']==1)
return i;
}
return -1;
}
}
方法二:
一個從前查詢,一個從後查詢,如果下標相等,說明只出現了一次
public int firstUniqChar(String s) {
for (int i = 0; i < s.length(); i++)
if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i)))
return i;
return -1;
}