zoukankan      html  css  js  c++  java
  • 剑指offer三十四之第一个只出现一次的字符

    一、题目

      在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置

    二、思路

      详见代码注释。

    三、代码

    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.Set;
    
    
    public class Solution {
        public int FirstNotRepeatingChar(String str) {
            if(str==null||str.length()==0){
                return -1;
            }
            
            //统计字符串的个数,注意用LinkedHashMap
            LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<Character, Integer>();
            for (char c : str.toCharArray()) {
                if (lhm.containsKey(c)) {
                    lhm.put(c, lhm.get(c) + 1);
                } else {
                    lhm.put(c, 1);
                }
            }
    
            //遍历map,寻找第一个只出现一次的数
            int num = 0;
            Set<Map.Entry<Character, Integer>> set = lhm.entrySet();
            for (Map.Entry<Character, Integer> es : set) {
                char key = es.getKey();
                int value = es.getValue();
                if (value == 1) {
                    num = key;
                    break;
                }
            }
    
            //查找索引index
            int index=0;
            
            for(int i=0;i<str.length();i++){
                if(str.charAt(i)==num){
                    index=i;
                    break;
                }
            }
            
            //返回索引的位置
            return index;
        }
    }
    View Code

    ---------------------------------------------

    参考链接:

    https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tqId=11187&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

  • 相关阅读:
    spring-mvc访问本地html文件
    好文收集
    jsp参数乱码解决
    ext window嵌jsp页面自适应
    正则学习(转)
    Error occurred during initialization of VM Incompatible initial and maximum heap sizes specified
    产品测试流程
    创建maven工程时报错,解决方案
    接口测试中如何利用cookies保持会话
    http协议基础
  • 原文地址:https://www.cnblogs.com/hezhiyao/p/7653779.html
Copyright © 2011-2022 走看看