URL Request Router

Asked at Google

Reported by the problem's creator, not verified

A web server picks a handler for each request by matching the request's URL against registered patterns. Implement this matching in a Router class.

Examples

  1. Example 1

    Input: init = [], operations = [["add_handler",["/users/{userId}/photo/{photoId}"]],["add_handler",["/users/delete"]],["get_handler",["/users/42/photo/7"]],["get_handler",["/users/delete"]],["get_handler",["/users/42"]],["get_handler",["/users/42/photo"]],["get_handler",["/photos"]],["add_handler",["/users/delete"]],["get_handler",["/users/delete"]]]

    Output: [null,null,"/users/{userId}/photo/{photoId}","/users/delete",null,null,null,null,"/users/delete"]

    Explanation: /users/42/photo/7 fits the placeholder pattern with userId = 42 and photoId = 7. /users/delete fits only the literal pattern. /users/42 and /users/42/photo have the wrong number of segments, /photos matches nothing, and registering /users/delete again changes nothing.

  2. Example 2

    Input: init = [], operations = [["add_handler",["/a/{x}/{z}"]],["add_handler",["/{y}/b/c"]],["get_handler",["/a/b/c"]]]

    Output: [null,null,"/a/{x}/{z}"]

    Explanation: Both patterns match /a/b/c. The first segment where they differ is the first one: literal a in /a/{x}/{z} versus placeholder {y} in /{y}/b/c, so the pattern that is literal there wins.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.