在字符串中找出第一个只出现一次的字符(Java实现)剑指

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_34122324/article/details/82891280



在字符串中找出第一个只出现一次的字符。

例:
输入:“abbaccdeff”
输出:‘d’

解析:

有三种方法
第一种:按顺序一个个把字符抽出来与后面的字符作对比。 时间复杂度O(n^2)
第二种:用类似哈希表的方式用来统计字符出现的次数。 时间复杂度O(n)
第三种:直接用哈希表的方式用来统计字符出现的字数。时间复杂度O(n)

第一种

    //时间复杂度O(n^2),因为indexOf方法复杂度为O(n)
    private void printFirstLetter1(String str){
        for (int i = 0; i < str.length(); i++) {
            //截去第i个字符
            String temp = str.substring(0, i) + str.substring(i + 1);
            //在剩余的字符串中搜索有没有与第i个字符相同的,没有的时候会返回-1
            int idx = temp.indexOf(str.charAt(i));
            //剩下的字符串中没有的,就是唯一的
            if (idx == -1) {
                String c = String.valueOf(str.charAt(i));
                System.out.println(c);
                break;
            }
        }
    }

第二种

    //用类似哈希表的方式用来统计字符出现的次数,时间复杂度O(n)
    private void printFirstLetter2(String str){
        int[] hash = new int[256];

        //统计字符出现的次数,存在hash数组中
        for (int i = 0; i < str.length(); i++) {
            int temp = str.charAt(i);
            hash[temp]++;
        }

        //按顺序进行遍历,将出现的此处为1的字符打印出来
        for (int i = 0; i < str.length(); i++) {
            int temp = str.charAt(i);
            if (hash[temp] == 1){
                char c = (char) temp;
                System.out.println(c);
                break;
            }
        }
    }

第三种

    //用哈希表的方式用来统计字符出现的字数,时间复杂度O(n)
    private void printFirstLetter3(String str) {
        HashMap<Character, Integer> hashMap = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
             if (hashMap.containsKey(str.charAt(i))){
                 int value = hashMap.get(str.charAt(i));
                 hashMap.put(str.charAt(i), value+1);
             }else {
                 hashMap.put(str.charAt(i), 1);
             }
        }

        for (int i = 0; i < str.length(); i++) {
            if (hashMap.get(str.charAt(i)) == 1){
                System.out.println(str.charAt(i));
                break;
            }

        }

    }

猜你喜欢

转载自blog.csdn.net/baidu_34122324/article/details/82891280