An API gateway chooses an upstream service from the request method and path. Route tables commonly combine literal paths, parameter segments, and catch-all routes, so matching must have explicit precedence rules.
Design an ApiGatewayRouter class:
ApiGatewayRouter(String[] methods, String[] patterns, String[] services) stores aligned route definitions.String route(String method, String path) returns the selected service or "NOT_FOUND".
Each pattern is made of slash-separated segments:
- A static segment such as
users matches the same text exactly. - A parameter segment such as
{id} matches exactly one non-empty segment. * may appear only as the final segment and matches one or more remaining segments.
The HTTP method must match exactly. Among matching routes, compare specificity from left to right using static > parameter > wildcard. At the first difference, the more specific segment wins. If two routes have identical specificity, choose the smaller input index.
Paths do not contain query strings, fragments, trailing slashes, or consecutive slashes. The root path is "/".
Example 1:
Input:
Output:
Explanation: The static me route is more specific than a parameter or wildcard. The parameter route matches one segment, while the deeper request requires the wildcard.
Example 2:
Input:
Output:
Explanation: Method matching happens before path precedence. The POST route accepts the first request, while no route accepts DELETE.
Constraints
1 <= methods.length == patterns.length == services.length <= 200- Methods and services are non-empty case-sensitive strings.
- Patterns and request paths start with
/ and contain at most 20 segments. - Parameter segments have the form
{name}. - A wildcard, when present, is the final segment.
- Static pattern segments do not begin with
{ and are not *. - At most
10^4 calls are made to route. - The constructor must copy the supplied arrays.