其他分享
首页 > 其他分享> > 力扣原题:387. 字符串中的第一个唯一字符

力扣原题:387. 字符串中的第一个唯一字符

作者:互联网

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

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

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

代码:
``/方法一:使用哈希表存储频数/
Map<Character,Integer> map=new HashMap<Character,Integer>();
for (char str:s.toCharArray()) { //遍历
map.put(str, map.getOrDefault(str, 0)+1);//getOrDefault获取hasp表中含该数的值+1,再存入哈希表中
}
for (int i = 0; i < s.length(); i++){ //二次遍历
if(map.get(s.charAt(i))==1) { //判断当前数在哈希表中是否存在,并且只出现一次,返回该数下标
return i;
}
}
return -1;

	/* 方法二:使用哈希表存储索引 */
	
	 Map<Character,Integer> position =new HashMap<Character,Integer>();
	 int n=s.length();
	 for (int i = 0; i <n; i++) {
		char ch =s.charAt(i);
		if(position.containsKey(ch))
		{
			position.put(ch,-1);
		}
		else{
			position.put(ch,i);
		}
	}
	 int first=n;
	 for(Map.Entry<Character,Integer> entry:position.entrySet())
	 {
		 int pos=entry.getValue();
		 if(pos!=-1&&pos<first)
		 {
			 first=pos;
		 }
	 }
	 if(first==n)
	 {
		 first=-1;
	 }
       return first;	``

标签:map,str,原题,int,表中,pos,力扣,哈希,387
来源: https://www.cnblogs.com/weifufa/p/15557350.html