[Swift]LeetCode736. Lisp 語法解析 | Parse Lisp Expression

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-hxyalguf-ev.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

You are given a string expressionrepresenting a Lisp-like expression to return the integer value of.git

The syntax for these expressions is given as follows.github

  • An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single integer.
  • (An integer could be positive or negative.)
  • A let-expression takes the form (let v1 e1 v2 e2 ... vn en expr), where let is always the string "let", then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let-expression is the value of the expression expr.
  • An add-expression takes the form (add e1 e2) where add is always the string "add", there are always two expressions e1, e2, and this expression evaluates to the addition of the evaluation of e1 and the evaluation of e2.
  • A mult-expression takes the form (mult e1 e2) where mult is always the string "mult", there are always two expressions e1, e2, and this expression evaluates to the multiplication of the evaluation of e1and the evaluation of e2.
  • For the purposes of this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally for your convenience, the names "add", "let", or "mult" are protected and will never be used as variable names.
  • Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on scope.

Evaluation Examples:express

Input: (add 1 2)
Output: 3

Input: (mult 3 (add 2 3))
Output: 15

Input: (let x 2 (mult x 5))
Output: 10

Input: (let x 2 (mult x (let x 3 y 4 (add x y))))
Output: 14
Explanation: In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.

Input: (let x 3 x 2 x)
Output: 2
Explanation: Assignment in let statements is processed sequentially.

Input: (let x 1 y 2 x (add x y) (add x y))
Output: 5
Explanation: The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.

Input: (let x 2 (add (let x 3 (let x 4 x)) x))
Output: 6
Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context
of the final x in the add-expression.  That final x will equal 2.

Input: (let a1 3 b2 (add a1 1) b2) 
Output 4
Explanation: Variable names can contain digits after the first character.

Note:數組

  • The given string expression is well formatted: There are no leading or trailing spaces, there is only a single space separating different components of the string, and no space between adjacent parentheses. The expression is guaranteed to be legal and evaluate to an integer.
  • The length of expression is at most 2000. (It is also non-empty, as that would not be a legal expression.)
  • The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.

給定一個相似 Lisp 語句的表達式 expression,求出其計算結果。微信

表達式語法以下所示:ide

  • 表達式能夠爲整數,let 語法,add 語法,mult 語法。表達式的結果老是一個整數。
  • (整數能夠是正整數、負整數、0)
  • let 語法表示爲 (let v1 e1 v2 e2 ... vn en expr), 其中 let語法老是以字符串 "let"來表示,接下來會跟隨一個或多個交替變量或表達式,也就是說,第一個變量 v1被分配爲表達式 e1 的值,第二個變量 v2 被分配爲表達式 e2 的值,以此類推;最終 let 語法的值爲 expr表達式的值。
  • add語法表示爲 (add e1 e2),其中 add 語法老是以字符串 "add"來表示,該語法老是有兩個表達式e1e2, 該語法的最終結果是 e1表達式的值與 e2 表達式的值之和。
  • mult語法表示爲 (mult e1 e2) ,其中 mult 語法老是以字符串"mult"表示, 該語法老是有兩個表達式 e1e2,該語法的最終結果是 e1 表達式的值與 e2 表達式的值之積。
  • 在該題目中,變量的命名以小寫字符開始,以後跟隨0個或多個小寫字符或數字。爲了方便,"add","let","mult"會被定義爲"關鍵字",不會在表達式的變量命名中出現。
  • 最後,要說一下範圍的概念。在作計算時,須要注意優先級,在最內層(根據括號)的表達式的值應該先計算,而後依次計算外層的表達式。咱們將保證每個測試的表達式都是合法的。有關範圍的更多詳細信息,請參閱示例。 

示例:函數

輸入: (add 1 2)
輸出: 3

輸入: (mult 3 (add 2 3))
輸出: 15

輸入: (let x 2 (mult x 5))
輸出: 10

輸入: (let x 2 (mult x (let x 3 y 4 (add x y))))
輸出: 14
解釋: 
表達式 (add x y), 在獲取 x 值時, 咱們應當由最內層依次向外計算, 首先遇到了 x=3, 因此此處的 x 值是 3.

輸入: (let x 3 x 2 x)
輸出: 2
解釋: let 語句中的賦值運算按順序處理便可

輸入: (let x 1 y 2 x (add x y) (add x y))
輸出: 5
解釋: 
第一個 (add x y) 計算結果是 3,而且將此值賦給了 x 。
第二個 (add x y) 計算結果就是 3+2 = 5 。

輸入: (let x 2 (add (let x 3 (let x 4 x)) x))
輸出: 6
解釋: 
(let x 4 x) 中的 x 的做用範圍僅在()以內。因此最終作加法操做時,x 的值是 2 。

輸入: (let a1 3 b2 (add a1 1) b2) 
輸出: 4
解釋: 
變量命名時能夠在第一個小寫字母后跟隨數字. 

注意:測試

  • 咱們給定的 expression 表達式都是格式化後的:表達式先後沒有多餘的空格,表達式的不一樣部分(關鍵字、變量、表達式)之間僅使用一個空格分割,而且在相鄰括號之間也沒有空格。咱們給定的表達式均爲合法的且最終結果爲整數。
  • 咱們給定的表達式長度最多爲 2000 (表達式也不會爲空,由於那不是一個合法的表達式)。
  • 最終的結果和中間的計算結果都將是一個 32 位整數。

Runtime: 384 ms
Memory Usage: 20.3 MB
 1 class Solution {
 2     func evaluate(_ expression: String) -> Int {        
 3         var m:[String:Int] = [String:Int]()
 4         return helper(expression, m)
 5     }
 6     
 7     func helper(_ str:String,_ m:[String:Int]) -> Int
 8     {
 9         var arr:[Character] = Array(str)
10         var m = m
11         if arr[0] == "-" || (arr[0] >= "0" && arr[0] <= "9")
12         {
13             return Int(str) ?? 0
14         }
15         else if arr[0] != "("
16         {
17             return m[str,default:0]
18         }
19         var s:String = str.subString(1, str.count - 2)
20         var cur:Int = 0
21         var cmd:String = parse(&s, &cur)
22         if cmd == "let"
23         {
24             while (true) {
25                 var str2 = parse(&s, &cur)
26                 if cur > s.count 
27                 {
28                     return helper(str2, m)
29                 }
30                 var t:String = parse(&s, &cur)
31                 m[str2] = helper(t, m)
32             }
33         }
34         else if cmd == "add"
35         {
36             return helper(parse(&s, &cur), m) + helper(parse(&s, &cur), m)
37         }
38         else if cmd == "mult"
39         {
40             return helper(parse(&s, &cur), m) * helper(parse(&s, &cur), m)
41         }    
42         return 0
43     }
44     
45     func parse(_ s:inout String,_ cur:inout Int) -> String
46     {
47         var end:Int = cur + 1
48         var t:Int = cur
49         var cnt:Int = 1
50         if s[cur] == "("
51         {
52             while (cnt != 0)
53             {
54                 if s[end] == "("
55                 {
56                     cnt += 1
57                 }
58                 else if s[end] == ")"
59                 {
60                     cnt -= 1
61                 }
62                 end += 1
63             }
64             
65         }
66         else
67         {
68             while (end < s.count && s[end] != " ")
69             {
70                 end += 1            
71             }
72             
73         }
74         cur = end + 1
75         return s.subString(t, end - t)
76     }
77 }
78 
79 extension String {
80     //subscript函數能夠檢索數組中的值
81     //直接按照索引方式截取指定索引的字符
82     subscript (_ i: Int) -> Character {
83         //讀取字符
84         get {return self[index(startIndex, offsetBy: i)]}
85     }
86     
87     // 截取字符串:指定索引和字符數
88     // - begin: 開始截取處索引
89     // - count: 截取的字符數量
90     func subString(_ begin:Int,_ count:Int) -> String {
91         let start = self.index(self.startIndex, offsetBy: max(0, begin))
92         let end = self.index(self.startIndex, offsetBy:  min(self.count, begin + count))
93         return String(self[start..<end]) 
94     }    
95 }
相關文章
相關標籤/搜索