First Unique Character in a String

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

unique->hashset.
but hashset can only do binary things, like if I find again, the only way to show I found again is remove this key, but what if they appear third time? do I have to re-add that?

so instead, I use hashmap.

class Solution {
    public int firstUniqChar(String s) {
        if (s == null || s.length() == 0) return -1;
        
        HashMap<Character, Boolean> map = new HashMap();
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), false);
            } else {
                map.put(s.charAt(i), true);
            }
        }
        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i))) { //if it is true, means this is the only one in whole string
                return i;
            }
        }
        return -1;
    }
}
posted @ 2020-09-13 00:46  EvanMeetTheWorld  阅读(5)  评论(0)    收藏  举报