doocs/leetcode · error · IllegalArgumentException

Invalid char:

Error message

Invalid char: 

What it means

In the Java solution for LeetCode 488 (Zuma Game), the board and hand strings are compressed into a compact numeric encoding: 'R'->0x1, 'G'->0x2, 'B'->0x3, 'W'->0x4, 'Y'->0x5, ' '->0x0. Any other character hits the default branch and throws IllegalArgumentException('Invalid char: ' + ch). It fires when input contains a character outside the five allowed colors plus space.

Source

Thrown at solution/0400-0499/0488.Zuma Game/Solution.java:160

        }

        long stateBits = 0;
        for (char ch : stateChars) {
            stateBits = (stateBits << 3) | Zuma.encode(ch);
        }
        return stateBits;
    }

    private static long encode(char ch) {
        return switch (ch) {
            case 'R' -> 0x1;
            case 'G' -> 0x2;
            case 'B' -> 0x3;
            case 'W' -> 0x4;
            case 'Y' -> 0x5;
            case ' ' -> 0x0;
            default  ->
                throw new IllegalArgumentException("Invalid char: " + ch);
        };
    }
}

View on GitHub (pinned to f84f361dc4)

Solutions

  1. Sanitize input before encoding: uppercase and strip whitespace/newlines
  2. Extend the switch with any additional valid characters your variant uses
  3. Fail fast with a clear message including the offending char (already done) and fix the data source
  4. Add a regex pre-check like input.matches("[RGBYW ]*") to validate before calling encode

Example fix

// before
encode("RGB\n"); // throws Invalid char: 

// after
encode("RGB\n".trim()); // ok
// or pre-validate: s.matches("[RGBYW ]*")
Defensive patterns

Strategy: validation

Validate before calling

if (!ch.matches("[RGBYW ]]*".replace("]*", "]*"))) throw new IllegalArgumentException("Invalid char: " + ch); // pre-check
boolean ok = s.chars().allMatch(c -> "RGBYW ".indexOf(c) >= 0);

Type guard

private static boolean isValidChar(char ch) { return ch=='R'||ch=='G'||ch=='B'||ch=='W'||ch=='Y'||ch==' '; }

Try / catch

try { encode(s); } catch (IllegalArgumentException e) { if (e.getMessage().startsWith("Invalid char:")) { /* sanitize and retry */ } else throw e; }

Prevention

When it happens

Trigger: Calling encode() with a board/hand string containing lowercase letters, digits, '\n', or any character other than R G B W Y and space; passing an untrimmed string with a tab or trailing newline.

Common situations: Feeding test data from a file without trimming newlines; case differences ('r' instead of 'R'); adapting the solver to a variant with extra colors (e.g. 'P' purple) without extending the switch; copy-paste introducing invisible characters.

Related errors


AI-assisted analysis of doocs/leetcode@f84f361dc4 (2026-08-27). Data as JSON: /api/errors/1abd914531110d89. Report an issue: GitHub.