Java实现统计字符串中各字母出现的次数(含有括号)。

发布时间 2023-03-22 21:11:49作者: 初寒~修

题目 写一个函数用来统计字符串中各字母出现的次数。

示例:
输入:X2Y3XZ,输出:X3Y3Z1;
输入:Z3X(XY)2,输出:X3Y2Z3;
输入:Z4(Y2(XZ2)3)2X2,输出:X8Y4Z16;

package com.interview.javabasic.exam;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        String output = countChars(input);
        System.out.println(output);
    }
    public static String countChars(String input) {
        HashMap<Character, Integer> charCount = new HashMap<>();
        countCharsHelper(input, 1, charCount);
        String output = "";
        for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
            output += entry.getKey() + entry.getValue().toString();
        }
        return output;
    }

    private static void countCharsHelper(String input, int count, HashMap<Character, Integer> charCount) {
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '(') {
                int endIndex = findMatchingParenthesis(input, i);
                int num = getNumberAfterParenthesis(input, endIndex + 1);
                countCharsHelper(input.substring(i + 1, endIndex), count * num, charCount);
                i = endIndex + Integer.toString(num).length();
            } else if (Character.isLetter(c)) {
                int num = getNumberAfterParenthesis(input, i + 1);
                charCount.put(c, charCount.getOrDefault(c, 0) + count * num);
            }
        }
    }

    private static int findMatchingParenthesis(String input, int startIndex) {
        int count = 1;
        for (int i = startIndex + 1; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '(') {
                count++;
            } else if (c == ')') {
                count--;
                if (count == 0) {
                    return i;
                }
            }
        }
        return -1;
    }

    private static int getNumberAfterParenthesis(String input, int startIndex) {
        //数字可能不止个位
        int endIndex = startIndex;
        while (endIndex < input.length() && Character.isDigit(input.charAt(endIndex))) {
            endIndex++;
        }
        //可能只有是1
        return endIndex == startIndex ? 1 : Integer.parseInt(input.substring(startIndex, endIndex));
    }

}