zoukankan      html  css  js  c++  java
  • 第一个只出现一次的字符


    在一个字符串(0 <= 字符串长度 <= 10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置,如果没有则返回 -1(需要区分大小写,从 0 开始计数)


    解题思路

    利用每个字母的 ASCII 码做 hash 来作为数组的下标。首先用一个长度为 58 的数组来存储每个字母出现的次数,为什么是 58 呢?是因为 A - Z 对应的 ASCII 码为 65-90,a - z 对应的 ASCII 码值为 97 - 122,而每个字母的 index = int(word) - 65,比如 g = 103 - 65 = 38,而数组中具体记录的内容是该字母出现的次数,最终遍历一遍字符串,找出第一个数组内容为 1 的字母就可以了,时间复杂度为 O(n)

    public class Solution {
        public int FirstNotRepeatingChar(String str) {
            if(str == null || str.length() == 0) {
                return -1;
            }
            int[] res = new int[58];
            for(int i = 0; i < str.length(); i++) {
                res[str.charAt(i) - 65]++;
            }
            for(int i = 0; i < res.length; i++) {
                if(res[str.charAt(i) - 65] == 1) {
                    return i;
                }
            }
            return -1;
        }
    }
    

    也可以使用 HashMap 来完成

    import java.util.Map;
    import java.util.HashMap;
    public class Solution {
        public int FirstNotRepeatingChar(String str) {
            if(str == null || str.length() == 0) {
                return -1;
            }
            Map<Character, Integer> map = new HashMap<>();
            for(int i = 0; i < str.length(); i++) {
                if(map.containsKey(str.charAt(i))) {
                    int count = map.get(str.charAt(i));
                    map.put(str.charAt(i), ++count);
                } else {
                    map.put(str.charAt(i), 1);
                }
            }
            for(int i = 0; i < str.length(); i++) {
                if(map.get(str.charAt(i)) == 1) {
                    return i;
                }
            }
            return -1;
        }
    }
    

  • 相关阅读:
    go系列之数组
    node.js 下依赖Express 实现post 4种方式提交参数
    javascript的数据类型
    工作中常用的mysql操作
    Linux如何查看进程、杀死进程、启动进程等常用命令
    局域网两台笔记本如何使用svn
    固定电话的验证
    phpexcel来做表格导出(多个工作sheet)
    char.js专门用来做数据统计图
    Out of resources when opening file 错误解决
  • 原文地址:https://www.cnblogs.com/Yee-Q/p/13834043.html
Copyright © 2011-2022 走看看