zoukankan      html  css  js  c++  java
  • 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;
    	}
    }
  • 相关阅读:
    oracle增加字段,循环
    mybatis批量插入和更新
    oracle触发器
    Java中<? extends T>和<? super T>的理解
    函数式编程
    mybaitis
    操作word
    服务大厅流程
    jdk动态代理
    操作系统
  • 原文地址:https://www.cnblogs.com/dongling/p/5792800.html
Copyright © 2011-2022 走看看