-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoal-parse-interpretation.js
54 lines (43 loc) · 1.06 KB
/
goal-parse-interpretation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
Goal Parser Interpretation (https://leetcode.com/problems/goal-parser-interpretation/)
- Given a string command consisting only 'G', '()' and/or '(al)'
- Interpret 'G' as 'G', '()' as 'o', and '(al)' as 'al'
- Return the interpreted strings concatenated in the original order
*/
// ---- Test Cases ----
const testCase1 = 'G()(al)' // Goal
const testCase2 = 'G()()()()(al)' // Gooooal
const testCase3 = '(al)G(al)()()G' // alGalooG
// ---- Solution ----
const stringMap = {
'G': 'G',
'()': 'o',
'(al)': 'al',
}
/**
* @param {string} command
* @return {string}
*/
const interpret = (command) => {
const result = []
let pointer = 0
let key = ''
while (pointer < command.length) {
key += command[pointer]
if (stringMap[key]) {
result.push(stringMap[key])
key = ''
}
pointer++
}
return result.join('')
}
console.log(interpret(testCase1)) // Goal
console.log(interpret(testCase2)) // Gooooal
console.log(interpret(testCase3)) // alGalooG
// ---- Space and Time Complexity ----
/*
command.length = n
Time: O(n)
Space: O(n)
*/