Rank commands in a command palette. Score a command against the query like this, ignoring case: walk the command's characters from left to right and match each query character at the first place it can go after the previous match (greedy). Each matched character earns 1 point, 2 more if it comes right after the previous matched character, and 3 more if it is the command's first character or follows a space, -, _, or /. If some query character can't be matched, the command is filtered out.
Write rankCommands(query, commands) that returns the matching commands, best first: higher score first, then shorter command first, then in character-code order (as < compares strings). An empty query matches everything with score 0.
Input: query = "gco", commands = ["Toggle Comments","Go to Config","Git: Commit"] Output: ["Git: Commit","Go to Config","Toggle Comments"]
Git: Commit and Go to Config both score 11 (g and c start words, and o follows c), so the shorter one comes first. Toggle Comments scores 8 because its g doesn't start a word.
Input: query = "", commands = ["b","a","cc"] Output: ["a","b","cc"]
With an empty query all score 0, so shorter first, then alphabetical.
0 <= query.length <= 500 <= commands.length <= 10^4, each up to 100 characters, all different.Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #717 Rank Command Palette Results. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.