Fork me on GitHub

【Offer】[50-1] 【第一个只出现一次的字符】

题目描述

在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出'b'。

牛客网刷题地址

思路分析

可以遍历一遍字符串,将其存在map里面,并统计出现的次数,返回出现次数为1时的位置

测试用例

  1. 功能测试:字符串中存在只出现一次的字符;字符串中不存在只出现一次的字符;字符串中所有字符都只出现一次。
  2. 特殊输入测试:字符串为nullptr指针。

Java代码

public class Offer050_01 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }

    public static int FirstNotRepeatingChar(String str) {
        return Solution1(str);
    }

    private static int Solution1(String str) {
        if (str.length() == 0 || str == null) {
            return -1;
        }
        HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (hashMap.containsKey(c)) {
                hashMap.put(c, hashMap.get(c) + 1);
            } else {
                hashMap.put(c, 1);
            }
        }
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (hashMap.get(c) == 1) {
                return i;
            }
        }
        return 0;
    }
    
    
    public int Solution2(String str) {
        if (str == null || str.length() == 0)
            return -1;
        int[] repetitions = new int[256];
        for (int i = 0; i < 256; i++)
            repetitions[i] = 0;
        for (int i = 0; i < str.length(); i++) {
            int loc = (int) str.charAt(i);
            repetitions[loc] += 1;
        }
        for (int i = 0; i < str.length(); i++) {
            int loc = (int) str.charAt(i);
            if (repetitions[loc] == 1)
                return i;
        }
        return -1;
    }

    private static void test1() {
    }
    private static void test2() {
    }
    private static void test3() {
    }
}

代码链接

剑指Offer代码-Java

posted @ 2019-08-25 18:24  这个世界~  阅读(124)  评论(0编辑  收藏  举报