在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Under a grammar given below, strings can represent a set of lowercase words. Let's use Grammar can best be understood through simple examples:
Formally, the 3 rules for our grammar:
Given an Example 1: Input: Example 2: Input: "{{a,z},a{b,c},{ab,z}}" Output: ["a","ab","ac","z"] Explanation: Each distinct word is written only once in the final answer. Constraints:
如果你熟悉 Shell 编程,那么一定了解过花括号展开,它可以用来生成任意字符串。 花括号展开的表达式可以看作一个由 花括号、逗号 和 小写英文字母 组成的字符串,定义下面几条语法规则:
给出表示基于给定语法规则的表达式 假如你希望以「集合」的概念了解此题,也可以通过点击 “显示英文描述” 获取详情。 示例 1: 输入:"{a,b}{c{d,e}}" 输出:["acd","ace","bcd","bce"] 示例 2: 输入:"{{a,z}, a{b,c}, {ab,z}}" 输出:["a","ab","ac","z"] 解释:输出中 不应 出现重复的组合结果。 提示:
Runtime: 16 ms
Memory Usage: 13.2 MB
1 class Solution { 2 func braceExpansionII(_ expression: String) -> [String] { 3 var str:String = expression 4 var pos:Int = 0 5 return Array(parseRule2(&str, &pos).sorted()) 6 } 7 8 func merge(_ a:Set<String>,_ b:Set<String>) -> Set<String> 9 { 10 if a.isEmpty {return b} 11 if b.isEmpty {return a} 12 var ans:Set<String> = Set<String>() 13 for v1 in a 14 { 15 for v2 in b 16 { 17 ans.insert(v1 + v2) 18 } 19 } 20 return ans 21 } 22 23 //{a,b,c} 24 func parseRule1(_ str:inout String,_ i:inout Int) -> Set<String> 25 { 26 var ans:Set<String> = Set<String>() 27 i += 1 28 ans = parseRule2(&str, &i) 29 i += 1 30 return ans 31 } 32 33 //{a,b},{c,d} 34 func parseRule2(_ str:inout String,_ i:inout Int) -> Set<String> 35 { 36 var ans:Set<String> = Set<String>() 37 ans = parseRule3(&str, &i) 38 let arrStr:[Character] = Array(str) 39 while(i < str.count) 40 { 41 if arrStr[i] != "," {break} 42 i += 1 43 let temp:Set<String> = parseRule3(&str, &i) 44 ans = ans.union(temp) 45 } 46 return ans 47 } 48 49 //a{c,d}b{e,f} 50 func parseRule3(_ str:inout String,_ i:inout Int) -> Set<String> 51 { 52 var ans:Set<String> = Set<String>() 53 let arrStr:[Character] = Array(str) 54 while(i < str.count) 55 { 56 if arrStr[i] == "}" || arrStr[i] == "," {break} 57 if arrStr[i] == "{" 58 { 59 let temp:Set<String> = parseRule1(&str, &i) 60 ans = merge(ans, temp) 61 } 62 else 63 { 64 var temp:Set<String> = Set<String>() 65 var tmpStr:String = String() 66 while(i < str.count && arrStr[i] <= "z" && arrStr[i] >= "a") 67 { 68 tmpStr.append(arrStr[i]) 69 i += 1 70 } 71 temp.insert(tmpStr) 72 ans = merge(ans,temp) 73 } 74 } 75 return ans 76 } 77 }
|
请发表评论