标签:1087 prime val ArrayList lists add result sb Brace
package LeetCode_1087 /** * 1087.Brace-Expansion (prime) * https://leetcode.com/problems/brace-expansion/ * * A string S represents a list of words. Each letter in the word has 1 or more options. * If there is one option, the letter is represented as is. * If there is more than one option, then curly braces delimit the options. * For example, "{a,b,c}" represents options ["a", "b", "c"]. For example, "{a,b,c}d{e,f}" represents the list ["ade", "adf", "bde", "bdf", "cde", "cdf"]. Return all words that can be formed in this manner, in lexicographical order. Example 1: Input: "{a,b}c{d,e}f" Output: ["acdf","acef","bcdf","bcef"] Example 2: Input: "abcd" Output: ["abcd"] Note: 1. 1 <= S.length <= 50 2. There are no nested curly brackets. 3. All characters inside a pair of consecutive opening and ending curly brackets are different. * */ class Solution { /* * solution: DFS, Time:O(2^n), Space:O(n) * 1. create list format, for example:{a,b}c{d,e}f => [[a,b], [c], [d, e]] * 2. dfs to create result * */ fun expand(s: String): Array<String?> { val result = ArrayList<String>() val lists = ArrayList<ArrayList<String>>() var i = 0 var j = 0 while (i < s.length) { val c = s[i] if (c != '{') { //is letter, append it lists.add(ArrayList(listOf(c.toString()))) } else { //keep track to find out all letter j = i while (j < s.length && s[j] != '}') { j++ } val rString = s.substring(i + 1, j) val rList = rString.split(",") rList.sorted() lists.add(ArrayList(rList)) //move the i to right i = j } i++ } dfs(0, StringBuilder(), lists, result) //set for result val arrays = arrayOfNulls<String>(result.size) for (i in result.indices) { arrays[i] = result[i] } return arrays } private fun dfs(index: Int, sb: StringBuilder, lists: ArrayList<ArrayList<String>>, res: ArrayList<String>) { //if enumerated all element in lists, add into res if (index == lists.size) { res.add(sb.toString()) return } for (str in lists[index]) { sb.append(str) dfs(index + 1, sb, lists, res) //for next level sb.setLength(sb.length - 1) } } }
标签:1087,prime,val,ArrayList,lists,add,result,sb,Brace 来源: https://www.cnblogs.com/johnnyzhao/p/15246698.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。