zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    浅谈prufer编码
    数据结构训练之三
    博弈论训练之一
    动态规划训练之十三
    杂题训练之七
    奇技淫巧训练之八
    浅谈博弈论
    浅谈卡特兰数
    奇技淫巧训练之七
    浅谈概率期望的一些例题
  • 原文地址:https://www.cnblogs.com/haoworld/p/offer501-di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu.html
Copyright © 2011-2022 走看看