• [leetcode]387. First Unique Character in a String


    public static int firstUniqChar(String s) {
            /*
            自己想的是用map存,检查是否有重复
            网上更好的答案是用一个数组存,用char的ascii码作为数组下标,记录出现几次,这样更加快
            以后遇到对char操作的时候,如果要建立哈希表,记住可以用ASCII码作为下标建立长度256的数组
             */
    //        int res = -1;
    //        Map<Character,Integer> map = new HashMap<>();
    //        char[] ch = s.toCharArray();
    //        for (int i = 0; i < ch.length; i++) {
    //            if (map.containsKey(ch[i]))
    //                map.put(ch[i],-1);
    //            else
    //                map.put(ch[i],i);
    //        }
    //        for (int i = 0; i < ch.length; i++) {
    //            if (map.get(ch[i])!=-1)
    //            {
    //                res = i;
    //                break;
    //            }
    //        }
    //        return res;
            int[] ch = new int[256];
            for (int i = 0; i < s.length(); i++) {
                ch[s.charAt(i)]++;
            }
            for (int i = 0; i < s.length(); i++) {
                if (ch[s.charAt(i)] ==1)
                    return i;
            }
            return -1;
        }
     以后遇到对char操作的时候,如果要建立哈希表,记住可以用ASCII码作为下标建立长度256的数组
  • 相关阅读:
    java变量类型
    java基本数据类型
    java对象和类
    java认识
    vue-随笔-transition
    vue-随笔-class-style
    vue-随笔-form-elements
    Constructing Roads*
    hdu3371 Connect the Cities
    hdu1879浙大计算机研究生复试上机(2008)继续畅通工程
  • 原文地址:https://www.cnblogs.com/stAr-1/p/8205741.html
Copyright © 2020-2023  润新知