Use LinkedHaspMap Count occurance of Character in String
class Solution {Method 2 (7s)
public int firstUniqChar(String s) {
if(s.length()==0) return -1;
LinkedHashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
}
}
for(Character key: map.keySet()){
Integer value = map.get(key);
if(value == 1){
return s.lastIndexOf(String.valueOf(key));
}
}
return -1;
}
}
This method faster than method 1 for 4 time.
class Solution {
public int firstUniqChar(String s) {
if(s.length()==0) return -1;
int[] counts = new int[26];
for(int i=0; i<s.length(); i++)
counts[s.charAt(i)-'a']++;
for(int i=0; i<s.length(); i++){
if(counts[s.charAt(i)-'a'] == 1)
return i;
}
return -1;
}
}
Hi, i tried out your algorithm but it doesn't give unique character. Maybe you want to change the method title to a more appropriate one ?
ReplyDelete