Convert String to Map
Difficulty: Medium · Topics: String Parsing, Map, Conversion · Acceptance: 50.0% of 2 submissions
Difficulty: Medium | Tags: String Parsing, Map, Conversion
Description
Given a string representation of key-value pairs, parse it into an actual Map.
The string follows formats like:
"key1=value1, key2=value2""{key1=value1, key2=value2}"
Handle nested maps and list values where possible.
Implement:
stringToMap(str) → Map<String, Object>
Examples
Example 1:
Input: "{name=Alice, age=30, city=NYC}"
Output: {"name": "Alice", "age": "30", "city": "NYC"}
Example 2:
Input: "host=localhost, port=8080, debug=true"
Output: {"host": "localhost", "port": "8080", "debug": "true"}
Example 3 — Nested:
Input: "{user={name=Alice, role=admin}, active=true}"
Output: {"user": {"name": "Alice", "role": "admin"}, "active": "true"}
Constraints
- Keys and values do not contain unescaped
=or,. - Leading/trailing whitespace around keys and values is trimmed.
- Curly braces wrapping the string are optional.
1 <= str.length <= 10^5
Hints
Hint 1
Split on ,, then split each token on =. Be careful with nested braces — don't split inside them.