Wednesday, April 1, 2020

[Java][Exerise] First Unique Character in a String

Method 1 (28s)
Use LinkedHaspMap Count occurance of Character in String
class Solution {
    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;
    }
}
Method 2 (7s)
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;
    }
}

1 comment :

  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