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.

Note: You may assume the string contain only lowercase letters.

import java.util.Hashtable;
public class Solution {
    public int firstUniqChar(String s) {
        Map<Character,Integer> table = new LinkedHashMap<Character, Integer>();
        for(char c:s.toCharArray()){
        	if(table.get(c)==null)
        		table.put(c, 1);
        	else{
        		table.put(c, table.get(c)+1);
        	}
        }
        Set<Character> set = table.keySet();
        for(char c:set){
        	if(table.get(c)==1)
        		return s.indexOf(c);
        }
        return -1;
    }
}


你可能感兴趣的:(LeetCode,算法,String)