剑指offer-第一个只出现一次的字符

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
 
使用map记录每个字符出现的次数,并查询第一个出现一次的字符
 1 public int FirstNotRepeatingChar(String str) {//map my
 2         LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
 3         for(int i=0;i<str.length();i++){
 4             char c = str.charAt(i);
 5             if(map.containsKey(c)){
 6                 map.put(c,map.get(c)+1);
 7             }
 8             else{
 9                 map.put(c,1);
10             }
11         }
12         Character c = null;
13         Iterator iter =map.entrySet().iterator();
14         while(iter.hasNext()){
15             Map.Entry entry = (Map.Entry) iter.next();
16             if(1 == (Integer)entry.getValue()){
17                 c = (Character) entry.getKey();
18                 break;
19             }
20         }
21         int re = -1;
22         if(c!=null){
23             for(int i=0;i<str.length();i++){
24                 if(c ==str.charAt(i)){
25                     re = i;
26                     break;
27                 }
28             }
29         }
30         return re;
31     }

 

优化后

public int FirstNotRepeatingChar(String str) {//map mytip
        Map<Character,Integer> map = new HashMap<>();
        for(int i=0;i<str.length();i++){
            char c = str.charAt(i);
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }
            else{
                map.put(c,1);
            }
        }
        int re = -1;
        for(int i=0;i<str.length();i++){
            if(map.get(str.charAt(i))==1){
                re = i;
                break;
            }
        }
        return re;
    }

 

 相关题

剑指offer 字符流中第一个不重复的字符 https://www.cnblogs.com/zhacai/p/10711074.html

posted @ 2019-04-15 12:48  月半榨菜  阅读(116)  评论(0编辑  收藏  举报