【牛客-算法笔试 3月24日华为机试题】给你一个纯数字字符串s,请返回连续单一数字子串的个数

题目描述

Description: 给你一个纯数字字符串s,请返回连续单一数字子串的个数

提示:

1 <= s.length <= 100

输入描述:

“11121”

解释:

只含单一字母的子串分别是:“111” 、“11”, “1” “2”

“111” 出现1次
“11” 出现2次
“1” 出现4次
“2” 出现1次
共 1 + 2 + 4 + 1 = 8

解题思路:

  1. 先求出所有子串
  2. 再判断子串是否都是相同字符
    /**
     * 暴力法
     * @param str
     * @return
     */
    public static int test_1(String str) {
    
    
        int res = 0;
        HashMap<String,Integer> map = new HashMap<>();
        for(int i = 0; i < str.length(); i++){
    
    
            for (int j = i+1; j<=str.length(); j++){
    
    
                map.put(str.substring(i,j),map.getOrDefault(str.substring(i,j),0)+ 1);
            }
        }
        System.out.println(map.toString());
        //遍历map的所有key
        for (String key:map.keySet()){
    
    
            //System.out.println("key= "+key+" and value= "+map.get(key));
            //判断key中的字符是否都是相同字符
            if (isSameChars(key)){
    
    
                System.out.println("key= "+key+" and value= "+map.get(key));
                res = res +map.get(key);
            }

        }

        return res;
    }

    public static boolean isSameChars (String str) throws IllegalArgumentException {
    
    
        if (str == null)
            throw new IllegalArgumentException("Input string should not be null.");
        else if (str.length() < 2)
            return true;
        char first = str.charAt(0);
        for (int i=1; i<str.length(); i++)
            if (str.charAt(i) != first)
                return false;
        return true;
    }

猜你喜欢

转载自blog.csdn.net/qq_35655602/article/details/115187582