Java Regex


  • 0

    After you have read the Solution, you will find that the regular expression solution is missing in Java. The following is it.

    import java.util.regex.*;
    
    class Solution {
        public String countOfAtoms(String formula) {
            final Stack<Map<String, Integer>> stack = new Stack<>();
            stack.push(new TreeMap<>());
            final Pattern pattern = Pattern.compile("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)");
            final Matcher matcher = pattern.matcher(formula);
            while (matcher.find()) {
                final String match = matcher.group();
                if (match.equals("(")) {
                    stack.push(new TreeMap<>());
                } else if (match.startsWith(")")) {
                    final Map<String, Integer> top = stack.pop();
                    final int multiple = match.length() > 1 ? Integer.parseInt(match.substring(1, match.length())) : 1;
                    for (final String name : top.keySet()) {
                        stack.peek().put(name, stack.peek().getOrDefault(name, 0) + top.get(name) * multiple);
                    }
                } else {
                    int i = 1;
                    while (i < match.length() && Character.isLowerCase(match.charAt(i))) {
                        i++;
                    }
                    final String name = match.substring(0, i);
                    final int count = i < match.length() ? Integer.parseInt(match.substring(i, match.length())) : 1;
                    stack.peek().put(name, stack.peek().getOrDefault(name, 0) + count);
                }
            }
            final StringBuilder sb = new StringBuilder();
            for (final String name : stack.peek().keySet()) {
                sb.append(name);
                final int count = stack.peek().get(name);
                if (count > 1) {
                    sb.append(String.valueOf(count));
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.