First Unique Character in a String

NO IMAGE

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.

思路:用hashmap統計,再掃一遍;

public class Solution {
public int firstUniqChar(String s) {
if(s == null || s.length() ==0){
return -1;
}
HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();
for(int i=0; i<s.length(); i  ){
char c = s.charAt(i);
if(hashmap.containsKey(c)){
hashmap.put(c, hashmap.get(c) 1);
} else {
hashmap.put(c, 1);
}
}
for(int i=0; i<s.length(); i  ){
char c = s.charAt(i);
if(hashmap.get(c) == 1){
return i;
}
}
return -1;
}
}

思路2:用array來統計,節省空間,並且快點。

public class Solution {
public int firstUniqChar(String s) {
if(s == null || s.length() ==0){
return -1;
}
int[] count = new int[256];
for(int i=0; i<s.length(); i  ){
int index = s.charAt(i)-'a';
count[index]  ;
}
for(int i=0; i<s.length(); i  ){
int index = s.charAt(i)-'a';
if(count[index] == 1){
return i;
}
}
return -1;
}
}