字符串中的第一个唯一字符

题目描述

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例:

s = “leetcode”
返回 0

s = “loveleetcode”
返回 2

提示:你可以假定该字符串只包含小写字母。

分析

1.定义HashMap,其中键是字符,值是字符出现的次数;
2.定义List,把HashMap中值=1的字符放入List;
3.比较List中字符的索引,取最小值

代码

class Solution {
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        for(Character c:s.toCharArray()) {
        	int count=1;
        	if(map.containsKey(c)) {
        		map.put(c, map.get(c)+1);
        		continue;
        	}
        	map.put(c, count);
        }
        List<Character> list = new ArrayList<>();
        
        for(Character c2 : map.keySet()) {
        	if(map.get(c2)==1) {
        		list.add(c2);
        	}
        }
        
        if(list.size()==0) {
        	return -1;
        }else {
        	int min = Integer.MAX_VALUE;
        	for(Character c3:list) {
        		min=s.indexOf(c3)<min?s.indexOf(c3):min;
        	}
        	return min;
        }
    }
}

优化

List是多余的。
只需要遍历字符串,如果当前索引下的字符对应的HashMap的值=1,就返回当前索引,结束即可。

class Solution {
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        for(Character c:s.toCharArray()) {
        	int count=1;
        	if(map.containsKey(c)) {
        		map.put(c, map.get(c)+1);
        		continue;
        	}
        	map.put(c, count);
        }
        for(int i=0;i<s.length();i++) {
        	if(map.get(s.charAt(i))==1) {
        		return i;
        	}
        }
        return -1;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值