387. First Unique Character in a String

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.
思路: 本题找第一次出现的非重复的字符的坐标, 首先我们需要把坐标给保存起来,还得把重复出现的字符给去掉,然后再从保存的坐标中找到最小的,即第一次出现的非重复坐标的位置。
我们可以用一个map来保存每个字母的坐标,如果字母重复出现,坐标就置为-1. 最后从map中找到value不为-1的最小值。

public class Solution {
    public int firstUniqChar(String s) {
        if (s == null || s.length() == 0) return -1;
        HashMap<Character, Integer> map = new HashMap<>();
        for(int i = 0; i < s.length(); i++) {
            Character letter = s.charAt(i);
            if (map.containsKey(letter)) {
                map.put(letter, -1);
            } else {
                map.put(letter, i);
            }
        }
        int min = s.length(); // find the min pos
        for(Map.Entry<Character, Integer> entry: map.entrySet() ) {
            if (entry.getValue() != -1) {
                if (min > entry.getValue()) {
                    min = entry.getValue();
                }
            }
        }
        return min == s.length() ? -1 : min;

    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s