第一个出现一次的字符——剑指offer(Java)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/dadajixxx/article/details/87904574
/*题目
 *在一个字符串中找到第一个只出现一次的字符。如输入acbacd,则输出b。
 *
 * */

/*思路
 *  要想找到这一个字母 必须全部遍历还要记录次数
 *  双层循环可以解决,但是时间复杂度为 o(n^2)
 *  利用hash结构,空间换时间,存储字母出现的次数, 时间复杂度变为,o(n)
 *  知识点: linkedhashMap 输入与输出位置一只 比hashMap稍慢,hashMap put与get可能不一致
 * */
 public int FirstNotRepeatChar(String str){

        if(str == null || str.length()==0)
            return -1;
        char[] c = str.toCharArray();
        LinkedHashMap<Character,Integer> hash = new LinkedHashMap<Character, Integer>();

        for (char item : c){
            if (hash.containsKey(item))
                hash.put(item,hash.get(item)+1);
            else
                hash.put(item,1);
        }

        for (int i = 0; i < str.length(); i++){
            //if(hash.get(c[i])==1)  这个也可以
            if(hash.get(str.charAt(i))==1)
                return i;
        }
        return -1;
    }

    public static void main(String[] ars){
        offer35_two test = new offer35_two();
        String str ="abccndkab";
        System.out.print(test.FirstNotRepeatChar(str));
    }

坚持,加油

猜你喜欢

转载自blog.csdn.net/dadajixxx/article/details/87904574