zoukankan      html  css  js  c++  java
  • [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的数组
  • 相关阅读:
    文件的基本操作
    ps工作界面
    HDU 6300
    HDU 6298
    HDU 2037
    HDU 2036
    Tesseract OCR
    What is the difference between position: static,relative,absolute,fixed
    How to Call a synchronize function asynchronizly in C#
    WCF note1
  • 原文地址:https://www.cnblogs.com/stAr-1/p/8205741.html
Copyright © 2011-2022 走看看