当前位置 博文首页 > 孙中明:LeetCode每日打卡-387. 字符串中的第一个唯一字符

    孙中明:LeetCode每日打卡-387. 字符串中的第一个唯一字符

    作者:[db:作者] 时间:2021-09-04 18:34

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

    难度简单429收藏分享切换为英文接收动态反馈

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

    示例:

    s = "leetcode"
    返回 0
    
    s = "loveleetcode"
    返回 2
    

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

    import java.util.*;
    class Solution {
    
        public int firstUniqChar(String s) {
            char[] chars = s.toCharArray();
            
            Map<Character,Integer> map = new HashMap<Character,Integer>();
            
            // 重复的字符顶为-1;
            for(int i=0;i<=s.length()-1;i++){
                if(map.containsKey(chars[i])){
                    map.put(chars[i],-1);
                }else{
                    map.put(chars[i],i);
                }
            }
            // 然后再便利一遍如果是第一个出现的不为-1 的我们就返回
            for(int i=0;i<=s.length()-1;i++){
               int value = map.get(chars[i]);
                if(value!=-1){
                    return value;
                }
                
            }
            return -1; 
        }
    }
    
    cs
    下一篇:没有了