字符串中第一个唯一字符

此博客链接:

字符串中第一个唯一字符

题目链接:

题目

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

 

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

 

 

 

题解

使用哈希表,找第一个value中只有一个数字的值

代码

 

class Solution {
    public int firstUniqChar(String s) {
      Map<Character,Integer> map=new HashMap();

      for(int i=0;i<s.length();i++){
          char ch=s.charAt(i);
          map.put(ch,map.getOrDefault(ch,0)+1);
      }
         
      for(int i=0;i<s.length();i++){
          if(map.get(s.charAt(i))==1)
          return i;
      }

return -1;
    }
}

 

结果

 

 

posted @ 2021-04-22 23:59  萍2樱释  阅读(46)  评论(0编辑  收藏  举报