387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.
找出字符串 s
中第一个不重复的字符,并返回他的序号
解法:
一开始就想着用map来记录每次字符出现的次数,然后找到出现一次的字符就返回序号就可以了
但是提交过后发现用时太久了,用了 111ms
class Solution {
public int firstUniqChar(String s) {
if(s.length()==0) return -1;
int solu = -1;
Map<Character,Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if(map.get(s.charAt(i))!= null){
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}else{
map.put(s.charAt(i),1);
}
}
for (int i = 0; i < s.length(); i++) {
if(map.get(s.charAt(i))==1) {
solu = i;
break;
}
}
return solu;
}
}//111ms
看了diss中的解法,发现用数组就会快很多很多,,思路还是一致的。
class Solution {
public int firstUniqChar(String s) {
int[] arr = new int[27];
for (int i = 0;i < s.length() ;i++ )
arr[s.charAt(i) - 'a'] ++;
for (int i = 0;i< s.length() ;i++ )
if(arr[s.charAt(i) - 'a'] == 1) return i;
return -1;
}
}//28ms