zoukankan      html  css  js  c++  java
  • 剑指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

  • 相关阅读:
    文件输入输出
    快速幂
    Vijos1512 SuperBrother打鼹鼠
    P2564 生日礼物
    P1886 滑动窗口
    P1540 机器翻译
    TYVj1939 玉蟾宫
    P1988 最大数
    二分图匹配
    [GDOI2017集训&做题记录&日记]
  • 原文地址:https://www.cnblogs.com/zhacai/p/10710018.html
Copyright © 2011-2022 走看看