문제
The builder pattern constructs a complex object step by step and produces the final result at the end, so callers can set the parts in any order.
Each part is a keyword, a space, and its text:
select <columns>: comma-separated column names (spaces around commas may vary). Optional; the default is*.from <table>: required.where <condition>,order <columns>,limit <n>: optional.
If a keyword appears more than once, the last one wins. Build the query in this fixed order, with single spaces:
SELECT <columns> FROM <table>[ WHERE <condition>][ ORDER BY <columns>][ LIMIT <n>]
In the SELECT list, trim each column and join them with , . All other texts are copied unchanged.
Implement query_builder(parts).
Input
parts: The parts, in any order.
Output
Return the SQL query string.
제약 조건
1 ≤ number of parts ≤ 20
At least one from part; each part has at most 100 characters
예시
입력:
parts = ["where age \u003e 18", "from users", "select name,age"]
예상 출력:
expected = "SELECT name, age FROM users WHERE age \u003e 18"
입력:
std::vector<std::string> parts = {"where age \u003e 18", "from users", "select name,age"};
예상 출력:
std::string expected = "SELECT name, age FROM users WHERE age \u003e 18";
입력:
string[] parts = new string[] {"where age \u003e 18", "from users", "select name,age"};
예상 출력:
string expected = "SELECT name, age FROM users WHERE age \u003e 18";
설명
The parts arrive out of order, but the query is always built as SELECT … FROM … WHERE …: "SELECT name, age FROM users WHERE age > 18".
입력:
parts = ["from orders", "limit 10", "order total DESC"]
예상 출력:
expected = "SELECT * FROM orders ORDER BY total DESC LIMIT 10"
입력:
std::vector<std::string> parts = {"from orders", "limit 10", "order total DESC"};
예상 출력:
std::string expected = "SELECT * FROM orders ORDER BY total DESC LIMIT 10";
입력:
string[] parts = new string[] {"from orders", "limit 10", "order total DESC"};
예상 출력:
string expected = "SELECT * FROM orders ORDER BY total DESC LIMIT 10";
설명
Without a select part the columns default to *: "SELECT * FROM orders ORDER BY total DESC LIMIT 10".
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
Store each part by its keyword first; build the text only at the end.
힌트 2
A later part with the same keyword replaces the earlier one.
힌트 3
Trim each column in the SELECT list and use * when there is no select part.
예상 복잡도
O(total length) time, O(total length) extra space
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.