Drill

ProblemsJava › dates

Read a duration a human typed

mediumdatesParsingStringsMathJava

A config file lets people write timeouts as "1h30m" instead of counting seconds, and the loader has to turn that into a number without trusting it.

parseDuration(text: string) → int

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int parseDuration(String text) {
    
}

Worked examples

CallResult
parseDuration("1h30m")5400
parseDuration("45s")45
parseDuration("2h")7200
parseDuration("90m")5400

Hint

Scan digits, then expect exactly one unit letter. Remember which units you have already taken so order and repeats are both caught by the same check.

Reference solution in Java
int parseDuration(String text) {
    Map<Character, Integer> rank = new HashMap<>();
    rank.put('h', 1); rank.put('m', 2); rank.put('s', 3);
    Map<Character, Integer> mult = new HashMap<>();
    mult.put('h', 3600); mult.put('m', 60); mult.put('s', 1);
    int i = 0, total = 0, last = 0;
    while (i < text.length()) {
        int n = 0, digits = 0;
        while (i < text.length() && Character.isDigit(text.charAt(i))) {
            n = n * 10 + (text.charAt(i) - '0'); i++; digits++;
        }
        if (digits == 0 || i >= text.length()) return -1;
        char u = text.charAt(i);
        if (!rank.containsKey(u) || rank.get(u) <= last) return -1;
        last = rank.get(u);
        total += n * mult.get(u);
        i++;
    }
    return total;
}

The same problem in another language

More dates problems in Java