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
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/7fits the placeholder pattern withuserId = 42andphotoId = 7./users/deletefits only the literal pattern./users/42and/users/42/photohave the wrong number of segments,/photosmatches nothing, and registering/users/deleteagain changes nothing.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: literalain/a/{x}/{z}versus placeholder{y}in/{y}/b/c, so the pattern that is literal there wins.