【题目】

找到第一个没有重复出现的字母

Given a string sfind the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

Example 3:

Input: s = "aabb"
Output: -1

 【思路】

待优化

用set做记录,遍历每一个字母,若之前没出现过,放进set;若之前出现(containsKey),则将set里的此字母赋值-1

注意continue跳出此次,因为HashMap会覆盖,否则后面put前面-1无用功了

最后再次遍历s,并查询set的情况,第一个值不是-1的返回

 

【代码】

class Solution {
    public int firstUniqChar(String s) {
        Map<Character,Integer> set=new HashMap<>();
        for(int i=0;i<s.length();i++){
            if(set.containsKey(s.charAt(i))){
                set.put(s.charAt(i),-1);
                continue;
            }
             set.put(s.charAt(i),i);
        }
        for(int i=0;i<s.length();i++){
            if(set.get(s.charAt(i))!=-1)
                return set.get(s.charAt(i));
        }
        return -1;
    }
}

 

 posted on 2021-08-22 22:44  alau  阅读(26)  评论(0编辑  收藏  举报