Leetcode算法比赛----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.

Java算法实现

public class Solution {
	public int firstUniqChar(String s) {
    	TreeSet<Character>set=new TreeSet<Character>();
		Map<Character,Integer>unique=new HashMap<Character, Integer>();
		for(int i=0;i<s.length();i++){
			Character ch=s.charAt(i);
			if(!set.contains(ch)){	//利用Set中每个元素都是唯一的这个属性,记录元素是否出现过
				set.add(ch);
				unique.put(ch, i);
			}
			else{
				if(unique.containsKey(ch)){
					unique.remove(ch);
				}
			}
		}
		
		int index=-1;
		Object[] values=unique.values().toArray();
		if(values.length>0){
			index=(int) values[0];
			for(int i=1;i<values.length;i++){
				if((int)values[i]<index){
					index=(int)values[i];
				}
			}
		}
		return index;
	}
}
原文地址:https://www.cnblogs.com/dongling/p/5792800.html