[LintCode] First Position Unique Character

浏览: 160 发布日期: 2018-01-01 分类: java

Problem

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

Example

Given s = "lintcode", return 0.

Given s = "lovelintcode", return 2.

Tags

Amazon Microsoft Bloomberg

Solution

public class Solution {
    public int firstUniqChar(String s) {
        //store string in an array
        char[] str = s.toCharArray();
        //use HashMap to check each character's frequency
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length; i++) {
            char ch = str[i];
            //reset duplicate chars to '#'
            if (map.containsKey(ch)) {
                str[map.get(ch)] = '#';
                str[i] = '#';
            } else {
                map.put(ch, i);
            }
        }
        int index = str.length;
        for (int i = 0; i < str.length; i++) {
            //find the first character that is not '#' and return its index
            if (str[i] != '#') {
                return i;
            }
        }
        //if no unique character, return -1
        return -1;
    }
}
返回顶部