question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
groups-of-special-equivalent-strings | C++ 100% | c-100-by-eridanoy-jfqp | \nclass Solution {\npublic:\n int numSpecialEquivGroups(const vector<string>& A) {\n unordered_set<string> us;\n for(const auto& s:A) {\n | eridanoy | NORMAL | 2020-11-25T23:09:34.748514+00:00 | 2020-11-25T23:09:34.748547+00:00 | 163 | false | ```\nclass Solution {\npublic:\n int numSpecialEquivGroups(const vector<string>& A) {\n unordered_set<string> us;\n for(const auto& s:A) {\n string s1,s2;\n for(int i=0; i<s.size(); ++++i) s1+=s[i];\n sort(s1.begin(),s1.end());\n for(int i=1; i<s.size(); ++++i) s2+=s[i];\n sort(s2.begin(),s2.end());\n us.insert(s1+s2);\n }\n return us.size();\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
groups-of-special-equivalent-strings | Easy Clean JavaScript | easy-clean-javascript-by-fl4sk-bxws | \nconst numSpecialEquivGroups = A => {\n \n const sortChars = str => {\n const odd = [...str].filter((_,i) => i%2);\n const even = [...str].filter((_,i | fl4sk | NORMAL | 2020-11-25T03:16:48.973220+00:00 | 2020-11-25T03:16:48.973265+00:00 | 66 | false | ```\nconst numSpecialEquivGroups = A => {\n \n const sortChars = str => {\n const odd = [...str].filter((_,i) => i%2);\n const even = [...str].filter((_,i) => !(i%2));\n return `${odd.sort().join(\'\')}${even.sort().join(\'\')}`\n };\n \n const set = new Set();\n A.forEach(str => set.add(sortChars(str)));\n return set.size;\n};\n\n\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Java 1 Line | java-1-line-by-wit-nq2b | \npublic int numSpecialEquivGroups(String[] array) {\n\treturn Arrays.stream(array).map(s -> IntStream.range(0, s.length()).boxed().collect(Collectors.toMap(i - | wit | NORMAL | 2020-11-24T03:21:47.163526+00:00 | 2020-11-24T03:21:47.163575+00:00 | 226 | false | ```\npublic int numSpecialEquivGroups(String[] array) {\n\treturn Arrays.stream(array).map(s -> IntStream.range(0, s.length()).boxed().collect(Collectors.toMap(i -> s.charAt(i) + 26 * (i & 1), i -> 1, Integer::sum)).entrySet().stream().sorted(Map.Entry.comparingByKey()).map(Object::toString).collect(Collectors.joining())).collect(Collectors.toSet()).size();\n}\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Easy Python 3 | easy-python-3-by-svr300-s3zn | \tclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n ls=[]\n for i in A:\n odd=i[0::2]\n even=i[1: | svr300 | NORMAL | 2020-10-30T02:46:17.393262+00:00 | 2020-10-30T02:46:17.393312+00:00 | 89 | false | \tclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n ls=[]\n for i in A:\n odd=i[0::2]\n even=i[1::2]\n ls.append(tuple(sorted(odd)+sorted(even)))\n\n return len(set(ls)) | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | easiest C++ | easiest-c-by-adiabatic123-90di | \nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& a) {\n unordered_set<string>s1;\n for(int i=0;i<a.size();i++){\n | adiabatic123 | NORMAL | 2020-10-21T12:07:24.168453+00:00 | 2020-10-21T12:07:24.168480+00:00 | 84 | false | ```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& a) {\n unordered_set<string>s1;\n for(int i=0;i<a.size();i++){\n string s=a[i];\n string odd="",even="";\n for(int i=0;i<s.length();i++){\n if(i%2==0)\n even+=s[i];\n else\n odd+=s[i];\n }\n sort(even.begin(),even.end());\n sort(odd.begin(),odd.end());\n s1.insert(even+odd);\n \n }\n return s1.size();\n }\n};\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Well, prime numbers helped | well-prime-numbers-helped-by-mesurajpand-rsan | \npublic int numSpecialEquivGroups(String[] A) {\n int len = A.length;\n int[] firstTwentySixPrimes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29 | mesurajpandey | NORMAL | 2020-09-28T01:38:30.999923+00:00 | 2020-09-28T01:38:30.999967+00:00 | 65 | false | ```\npublic int numSpecialEquivGroups(String[] A) {\n int len = A.length;\n int[] firstTwentySixPrimes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};\n Set<String> result = new HashSet<>();\n for(int i=0;i<len;i++) {\n int strLen = A[i].length();\n int oddIndicesNum = 1;\n int evenIndicesNum = 1;\n for(int j=0;j<strLen;j++) {\n char ch = A[i].charAt(j);\n if (j%2 != 0) oddIndicesNum *= firstTwentySixPrimes[ch-\'a\'];\n else evenIndicesNum *= firstTwentySixPrimes[ch-\'a\'];\n }\n result.add(""+oddIndicesNum+"-"+evenIndicesNum);\n }\n return result.size();\n }\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | JAVA O(26*N) | java-o26n-by-gobblin_insights-qoma | \nclass Solution {\n private String evenOdd(String str){\n int n = str.length();\n int [] even = new int[26];\n int [] odd = new int[26] | gobblin_insights | NORMAL | 2020-08-27T16:33:08.177137+00:00 | 2020-08-27T16:33:08.177192+00:00 | 201 | false | ```\nclass Solution {\n private String evenOdd(String str){\n int n = str.length();\n int [] even = new int[26];\n int [] odd = new int[26];\n for(int i=0;i<n;i++){\n char c = str.charAt(i);\n if(i%2==0){\n even[c-\'a\']++;\n }else{\n odd[c-\'a\']++;\n }\n }\n StringBuilder sb = new StringBuilder();\n for(int x:even)sb.append(x);\n for(int x:odd)sb.append(x);\n return sb.toString();\n }\n public int numSpecialEquivGroups(String[] A) {\n Set<String> set = new HashSet<String>();\n for(String str : A){\n String key = evenOdd(str);\n set.add(key);\n }\n return set.size();\n }\n}\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | C++, easy-understand, set, dict | c-easy-understand-set-dict-by-zxspring21-9ho5 | \nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n set<string> s;\n for(int i=0; i<A.size(); ++i){\n int | zxspring21 | NORMAL | 2020-08-26T13:07:46.242210+00:00 | 2020-08-26T13:07:46.242243+00:00 | 205 | false | ```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n set<string> s;\n for(int i=0; i<A.size(); ++i){\n int even[26]={0}, odd[26]={0};\n string index;\n for(int j=0; j< A[i].size(); ++j){\n if(j%2) even[A[i][j]-\'a\']++;\n else odd[A[i][j]-\'a\']++;\n }\n for(int i=0;i<26;++i) index+=to_string(even[i]);\n for(int i=0;i<26;++i) index+=to_string(odd[i]);\n s.insert(index);\n }\n return s.size();\n }\n};\n``` | 1 | 1 | ['C'] | 0 |
groups-of-special-equivalent-strings | Python One Liner | python-one-liner-by-frank_paul-lw3q | \nclass Solution: \n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len(set(\'\'.join(sorted(stri[i] for i in range(len(stri)) | frank_paul | NORMAL | 2020-07-24T05:02:02.163366+00:00 | 2020-07-24T05:04:45.387840+00:00 | 283 | false | ```\nclass Solution: \n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len(set(\'\'.join(sorted(stri[i] for i in range(len(stri)) if i%2==0)) + \'\'.join(sorted(stri[i] for i in range(len(stri)) if i%2!=0)) for stri in A))\n``` | 1 | 6 | ['Python', 'Python3'] | 0 |
groups-of-special-equivalent-strings | easy understanding c++ using set and count array | easy-understanding-c-using-set-and-count-5h5m | \nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string>s;\n for(int i=0;i<A.size();i++)\n | imsoundharvidhu | NORMAL | 2020-06-07T07:49:02.217793+00:00 | 2020-06-07T07:49:02.217830+00:00 | 178 | false | ```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string>s;\n for(int i=0;i<A.size();i++)\n s.insert(createhash(A[i]));\n return s.size();\n }\n static string createhash(string a)\n {\n string res="";\n vector<int>even(26,0);\n vector<int>odd(26,0);\n for(int i=0;i<a.size();i++)\n {\n if(i%2==0)\n {\n even[a[i]-\'a\']++;\n }\n else\n {\n odd[a[i]-\'a\']++;\n }\n }\n for(int i=0;i<26;i++)\n {\n while(even[i])\n {\n res+=to_string(i+\'a\');\n even[i]--;\n }\n }\n res+=\'.\';\n for(int i=0;i<26;i++)\n {\n while(odd[i])\n {\n res+=to_string(i+\'a\');\n odd[i]--;\n }\n }\n return res;\n }\n};\n```\n | 1 | 0 | ['C', 'Ordered Set', 'C++'] | 0 |
groups-of-special-equivalent-strings | Python soln | python-soln-by-vharshal1994-mk3j | \nclass Solution(object):\n def numSpecialEquivGroups(self, A):\n """\n :type A: List[str]\n :rtype: int\n """\n #https:// | vharshal1994 | NORMAL | 2020-05-15T14:17:53.857357+00:00 | 2020-05-15T14:17:53.857411+00:00 | 137 | false | ```\nclass Solution(object):\n def numSpecialEquivGroups(self, A):\n """\n :type A: List[str]\n :rtype: int\n """\n #https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/358795/python3-detail-explanation-of-special-equivalent\n \n if len(A) == 1:\n return 1\n \n res = set()\n for string in A:\n even_indexed_string = string[0::2]\n sorted_even_indexed_string = "".join(sorted(even_indexed_string))\n \n odd_indexed_string = string[1::2]\n sorted_odd_indexed_string = "".join(sorted(odd_indexed_string))\n \n sorted_odd_even = sorted_even_indexed_string + sorted_odd_indexed_string\n res.add(sorted_odd_even)\n\n return len(res)\n``` | 1 | 0 | [] | 1 |
groups-of-special-equivalent-strings | Groups of Special-Equivalent Strings | groups-of-special-equivalent-strings-by-lcthn | ```\n // Runtime: 6 ms, faster than 82.18% of Java online submissions for Groups of Special-Equivalent Strings.\n // Memory Usage: 39.3 MB, less than 7.69 | tenzindadhul | NORMAL | 2020-05-15T08:55:22.951990+00:00 | 2020-05-15T08:55:22.952026+00:00 | 55 | false | ```\n // Runtime: 6 ms, faster than 82.18% of Java online submissions for Groups of Special-Equivalent Strings.\n // Memory Usage: 39.3 MB, less than 7.69% of Java online submissions for Groups of Special-Equivalent Strings.\n public int numSpecialEquivGroups(String[] A) {\n Set<String> uniqueSet = new HashSet<>();\n\n for (String str : A) {\n StringBuilder evenIndStr = new StringBuilder();\n StringBuilder oddIndStr = new StringBuilder();\n\n for (int i = 0; i < str.length(); ++i) {\n if (i % 2 == 0) \n evenIndStr.append(str.charAt(i));\n else \n oddIndStr.append(str.charAt(i));\n }\n char[] evenStr = evenIndStr.toString().toCharArray();\n char[] oddStr = oddIndStr.toString().toCharArray();\n Arrays.sort(evenStr);\n Arrays.sort(oddStr);\n\n uniqueSet.add(new String(evenStr) + new String(oddStr));\n }\n\n return uniqueSet.size(); \n } | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Python3 Solution - Sort | python3-solution-sort-by-ma_e-bp4j | class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n\n # sort string by index \n def F(s):\n odd, even = "", " | ma_e | NORMAL | 2020-04-07T21:36:07.155472+00:00 | 2020-04-07T21:36:07.155507+00:00 | 84 | false | class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n\n # sort string by index \n def F(s):\n odd, even = "", ""\n for i in range(len(s)):\n if i % 2 == 0: even += s[i]\n else: odd += s[i]\n return "".join(sorted(even) + sorted(odd))\n \n return len(set([F(s) for s in A])) | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | [Swift] Character Counting | swift-character-counting-by-alptekin35-bngz | \nclass Solution {\n func numSpecialEquivGroups(_ A: [String]) -> Int {\n var set:Set<String> = Set()\n for item in A{\n let chars = | alptekin35 | NORMAL | 2020-03-16T04:22:28.401645+00:00 | 2020-03-16T04:22:28.401677+00:00 | 54 | false | ```\nclass Solution {\n func numSpecialEquivGroups(_ A: [String]) -> Int {\n var set:Set<String> = Set()\n for item in A{\n let chars = Array(item)\n var arr:[Character] = Array(repeating: "0", count: 52)\n for i in 0..<chars.count{\n if i % 2 == 0{\n let val = Int(String(arr[Int(chars[i].asciiValue!) - 97]))! + 1\n arr[Int(chars[i].asciiValue!) - 97] = Character(val.description)\n }else{\n let val = Int(String(arr[Int(chars[i].asciiValue!) - 97 + 26]))! + 1\n arr[Int(chars[i].asciiValue!) - 97 + 26] = Character(val.description) \n }\n }\n set.insert(String(arr))\n }\n return set.count\n }\n}\n``` | 1 | 0 | ['Swift'] | 0 |
groups-of-special-equivalent-strings | python3 simple solution | python3-simple-solution-by-boekveld-gtrw | If two strings are special-equivalent,\nthey share the following tuple:\n\n(sorted string made of characters of the original strings of even indices,\nsorted st | boekveld | NORMAL | 2020-01-21T13:12:26.881946+00:00 | 2020-01-21T13:13:54.579956+00:00 | 131 | false | If two strings are special-equivalent,\nthey share the following tuple:\n\n(sorted string made of characters of the original strings of even indices,\nsorted str. made of chars. of the orig. strs. of odd indices)\n\nTherefore, if we make such tuples from each string and put into a set,\nthe length of the set is the answer. \n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n ans = set()\n ln = len(A[0])\n ceven, codd = [], []\n \n for i in A:\n for j in range(ln):\n if j % 2 == 0:\n ceven.append(i[j])\n \n else:\n codd.append(i[j])\n \n ceven.sort()\n codd.sort()\n ans.add((\'\'.join(ceven), \'\'.join(codd)))\n ceven.clear()\n codd.clear()\n \n return len(ans)\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Java Solution | java-solution-by-prjadhav-amag | ```\nclass Solution {\n public int numSpecialEquivGroups(String[] A) {\n Set set=new HashSet();\n for(String s:A){\n int[] evenChars | prjadhav | NORMAL | 2019-12-30T23:23:31.472943+00:00 | 2019-12-30T23:23:31.472976+00:00 | 157 | false | ```\nclass Solution {\n public int numSpecialEquivGroups(String[] A) {\n Set<String> set=new HashSet();\n for(String s:A){\n int[] evenChars=new int[26];\n int[] oddChars=new int[26];\n for(int i=0;i<s.length();i++){\n if(i%2==0){\n evenChars[s.charAt(i)-\'a\']++;\n }\n else{\n oddChars[s.charAt(i)-\'a\']++;\n }\n }\n set.add(Arrays.toString(evenChars)+Arrays.toString(oddChars));\n }\n return set.size();\n }\n} | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | C# Solution with LINQ | c-solution-with-linq-by-mhorskaya-dqpx | \npublic int NumSpecialEquivGroups(string[] A) {\n\treturn A.Select(Order).Distinct().Count();\n\n\tstring Order(string s) {\n\t\tvar chars = s.Select((c, i) => | mhorskaya | NORMAL | 2019-12-23T11:51:31.678590+00:00 | 2019-12-23T11:51:31.678622+00:00 | 63 | false | ```\npublic int NumSpecialEquivGroups(string[] A) {\n\treturn A.Select(Order).Distinct().Count();\n\n\tstring Order(string s) {\n\t\tvar chars = s.Select((c, i) => (i, c)).ToArray();\n\t\tvar evens = chars.Where(t => t.i % 2 == 0).Select(t => t.c).OrderBy(c => c);\n\t\tvar odds = chars.Where(t => t.i % 2 == 1).Select(t => t.c).OrderBy(c => c);\n\n\t\treturn new string(evens.Concat(odds).ToArray());\n\t}\n}\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Count the characters at even and odd positions | count-the-characters-at-even-and-odd-pos-oazn | csharp\npublic int NumSpecialEquivGroups(string[] A)\n{\n\tHashSet<string> groupCount = new HashSet<string>();\n\n\tforeach (var a in A)\n\t{\n\t\tint[] frequen | christris | NORMAL | 2019-11-20T02:46:19.716393+00:00 | 2019-11-20T02:51:22.687782+00:00 | 112 | false | ```csharp\npublic int NumSpecialEquivGroups(string[] A)\n{\n\tHashSet<string> groupCount = new HashSet<string>();\n\n\tforeach (var a in A)\n\t{\n\t\tint[] frequency = new int[26 * 2];\n\t\tfor (int i = 0; i < a.Length; i++)\n\t\t{\n\t\t\tif (i % 2 == 0)\n\t\t\t{\n\t\t\t\tfrequency[a[i] - \'a\']++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfrequency[26 + a[i] - \'a\']++;\n\t\t\t}\n\t\t}\n\n\t\tstring key = string.Join(",", frequency);\n\t\tgroupCount.Add(key);\n\t}\n\n\treturn groupCount.Count;\n}\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Brute Force And Optimized Solution in Cpp! | brute-force-and-optimized-solution-in-cp-vb13 | Here we have to sort substrings so nlogn!\n\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& a) {\n map<string,vector<string>>m; | sanjaygarg | NORMAL | 2019-10-22T11:27:23.642769+00:00 | 2019-10-22T11:27:23.642807+00:00 | 71 | false | Here we have to sort substrings so nlogn!\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& a) {\n map<string,vector<string>>m;\n int count=0;\n int n=a.size();\n for(int i=0;i<n;i++)\n {\n string odd="";\n string even="";\n for(int j=0;j<a[i].length();j++)\n {\n if(j%2==0)\n even=even+a[i][j];\n else\n odd=odd+a[i][j];\n }\n sort(even.begin(),even.end());\n sort(odd.begin(),odd.end());\n string res=even+odd;\n m[res].push_back(a[i]);\n }\n return m.size();\n }\n};\n```\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& a) {\n set<vector<int>>s;\n int count=0;\n int n=a.size();\n for(int i=0;i<n;i++)\n {\n vector<int>count(52,0);\n for(int j=0;j<a[i].length();j++)\n {\n if(j%2==0)\n count[a[i][j]-\'a\']++;\n else\n count[a[i][j]-\'a\'+26]++;\n }\n s.insert(count);\n }\n return s.size();\n }\n};\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Go golang clean solution | go-golang-clean-solution-by-leaf_peng-dsuz | Runtime: 4 ms, faster than 71.43% of Go online submissions for Groups of Special-Equivalent Strings.\nMemory Usage: 4.3 MB, less than 100.00% of Go online submi | leaf_peng | NORMAL | 2019-08-08T01:07:10.763715+00:00 | 2019-08-08T01:07:10.763752+00:00 | 79 | false | Runtime: 4 ms, faster than 71.43% of Go online submissions for Groups of Special-Equivalent Strings.\nMemory Usage: 4.3 MB, less than 100.00% of Go online submissions for Groups of Special-Equivalent Strings.\n\n```go\nfunc numSpecialEquivGroups(A []string) int {\n\n\ttmp := make(map[string]int)\n \n\tfor _, v := range A {\n\n\t\todd, even := []rune{}, []rune{}\n\n\t\tfor I, V := range v {\n\n\t\t\tif I%2 == 0 {\n\t\t\t\teven = append(even, V)\n\t\t\t} else {\n\t\t\t\todd = append(odd, V)\n\t\t\t}\n\n\t\t}\n\t\tsort.Slice(even, func(i int, j int) bool { return even[i] < even[j] })\n\t\tsort.Slice(odd, func(i int, j int) bool { return odd[i] < odd[j] })\n\t\ttemp := append(even, odd...)\n\t\ttmp[string(temp)]++\n\t}\n\n\treturn len(tmp)\n\n}\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | Python one liner | python-one-liner-by-josephzheng-f9r4 | \nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len(set(\'\'.join(sorted(w[::2]) + sorted(w[1::2])) for w in A))\n | josephzheng | NORMAL | 2019-07-29T17:19:08.086183+00:00 | 2019-07-29T17:19:08.086215+00:00 | 118 | false | ```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len(set(\'\'.join(sorted(w[::2]) + sorted(w[1::2])) for w in A))\n``` | 1 | 0 | [] | 0 |
groups-of-special-equivalent-strings | JS simple solution with explanation | js-simple-solution-with-explanation-by-y-43pp | We can calculate the signature of each word in the word array, and see how many distinct word signature there are, which would be the result. The signature is d | yushi_lu | NORMAL | 2019-07-17T03:08:02.937824+00:00 | 2019-07-17T03:08:02.937871+00:00 | 225 | false | We can calculate the *signature* of each word in the word array, and see how many distinct *word signature* there are, which would be the result. The *signature* is defined as:\n* extract all even-indexed chars and sort them\n* extract all odd-indexed chars and sort them\n* combine the above two\n\nTake the word "abccba" as example:\n```\noriginal word: abccba\neven-indexed chars: a c b --sort--> a b c --combine--> abc\nodd-indexed chars: b c a --sort--> a b c --combine--> abc\ncombine: abcabc\n```\n"abcabc" would be the signature for "abccba".\n```\n\nvar numSpecialEquivGroups = function(A) {\n let s = new Set()\n for (let w of A) {\n let tmp = helper(w)\n s.add(tmp)\n }\n return s.size\n};\n\nconst helper = function(s) {\n if (s.length <= 1)\n return s\n let fst = \'\', sec = \'\'\n for (let i = 0; i < s.length; i += 2)\n fst += s[i]\n fst = fst.split(\'\').sort().join(\'\')\n for (let i = 1; i < s.length; i += 2)\n sec += s[i]\n sec = sec.split(\'\').sort().join(\'\')\n return fst + sec\n}\n``` | 1 | 0 | ['JavaScript'] | 0 |
groups-of-special-equivalent-strings | Python Sol for Starters - EXTREMELY EASY | python-sol-for-starters-extremely-easy-b-vecr | python\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n length = len(A)\n res = set()\n for item in A:\n | deadline_killer_mzq | NORMAL | 2019-06-14T15:20:05.589896+00:00 | 2019-06-14T15:20:05.589936+00:00 | 171 | false | ```python\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n length = len(A)\n res = set()\n for item in A:\n odds = item[::2]\n evens = item[1::2]\n res.add((str(sorted(odds)),str(sorted(evens))))\n return len(res)\n``` | 1 | 0 | [] | 1 |
groups-of-special-equivalent-strings | c++ beat 99% with explanation | c-beat-99-with-explanation-by-barorz-g7ii | \tafter realizing the question, all we have to do is the check if odd/even position pattern is the same between two string.\n\tfor instance : "abcdefggyy"\n\tod | barorz | NORMAL | 2019-05-27T07:30:25.936459+00:00 | 2019-05-27T07:34:05.717241+00:00 | 201 | false | \tafter realizing the question, all we have to do is the check if odd/even position pattern is the same between two string.\n\tfor instance : "abcdefggyy"\n\todd pattern : "acegy"\n\teven pattern : "bdfgy"\n\twe can simply check those pattern after sorting.\n\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n map<std::pair<string,string>,int> mymap; // key:pattern pair\n for(int i = 0 ; i < A.size() ; i++){\n string s[2];\n for(int j = 0 ; j < A[i].length() ; j++)\n s[j%2]+= A[i][j];\n sort(s[0].begin(),s[0].end()),sort(s[1].begin(),s[1].end());\n mymap[{s[0],s[1]}]++;\n }\n return mymap.size();\n }\n};\n``` | 1 | 0 | [] | 0 |
mini-parser | An Java Iterative Solution | an-java-iterative-solution-by-alexthegre-sc7f | This approach will just iterate through every char in the string (no recursion).\n If encounters '[', push current NestedInteger to stack and start a new one.\n | alexthegreat | NORMAL | 2016-08-14T18:30:49.969000+00:00 | 2018-10-25T23:29:41.313662+00:00 | 28,565 | false | This approach will just iterate through every char in the string (no recursion).\n* If encounters '[', push current NestedInteger to stack and start a new one.\n* If encounters ']', end current NestedInteger and pop a NestedInteger from stack to continue.\n* If encounters ',', append a new number to curr NestedInteger, if this comma is not right after a brackets.\n* Update index l and r, where l shall point to the start of a integer substring, while r shall points to the end+1 of substring.\n\n\nJava Code:\n\n public NestedInteger deserialize(String s) {\n if (s.isEmpty())\n return null;\n if (s.charAt(0) != '[') // ERROR: special case\n return new NestedInteger(Integer.valueOf(s));\n \n Stack<NestedInteger> stack = new Stack<>();\n NestedInteger curr = null;\n int l = 0; // l shall point to the start of a number substring; \n // r shall point to the end+1 of a number substring\n for (int r = 0; r < s.length(); r++) {\n char ch = s.charAt(r);\n if (ch == '[') {\n if (curr != null) {\n stack.push(curr);\n }\n curr = new NestedInteger();\n l = r+1;\n } else if (ch == ']') {\n String num = s.substring(l, r);\n if (!num.isEmpty())\n curr.add(new NestedInteger(Integer.valueOf(num)));\n if (!stack.isEmpty()) {\n NestedInteger pop = stack.pop();\n pop.add(curr);\n curr = pop;\n }\n l = r+1;\n } else if (ch == ',') {\n if (s.charAt(r-1) != ']') {\n String num = s.substring(l, r);\n curr.add(new NestedInteger(Integer.valueOf(num)));\n }\n l = r+1;\n }\n }\n \n return curr;\n } | 116 | 0 | [] | 19 |
mini-parser | Python & C++ solutions | python-c-solutions-by-stefanpochmann-nxiu | Python using eval:\n\n def deserialize(self, s):\n def nestedInteger(x):\n if isinstance(x, int):\n return NestedInteger(x)\ | stefanpochmann | NORMAL | 2016-08-14T15:00:24.807000+00:00 | 2018-10-19T19:11:43.069539+00:00 | 17,409 | false | ## Python using `eval`:\n\n def deserialize(self, s):\n def nestedInteger(x):\n if isinstance(x, int):\n return NestedInteger(x)\n lst = NestedInteger()\n for y in x:\n lst.add(nestedInteger(y))\n return lst\n return nestedInteger(eval(s))\n\n## Python one-liner\n\n def deserialize(self, s):\n return NestedInteger(s) if isinstance(s, int) else reduce(lambda a, x: a.add(self.deserialize(x)) or a, s, NestedInteger()) if isinstance(s, list) else self.deserialize(eval(s))\n\n## Python Golf (136 bytes or 31 bytes)\n```\nclass Solution:deserialize=d=lambda S,s,N=NestedInteger:s<[]and N(s)or s<''and reduce(lambda a,x:a.add(S.d(x))or a,s,N())or S.d(eval(s))\n```\nOr abusing how the judge judges (yes, this gets accepted):\n```\nclass Solution:deserialize=eval\n```\n\n## Python parsing char by char\n\nHere I turned the input string into a list with sentinel for convenience.\n\n def deserialize(self, s):\n def nestedInteger():\n num = ''\n while s[-1] in '1234567890-':\n num += s.pop()\n if num:\n return NestedInteger(int(num))\n s.pop()\n lst = NestedInteger()\n while s[-1] != ']':\n lst.add(nestedInteger())\n if s[-1] == ',':\n s.pop()\n s.pop()\n return lst\n s = list(' ' + s[::-1])\n return nestedInteger()\n\n## C++ using `istringstream`\n```\nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n istringstream in(s);\n return deserialize(in);\n }\nprivate:\n NestedInteger deserialize(istringstream &in) {\n int number;\n if (in >> number)\n return NestedInteger(number);\n in.clear();\n in.get();\n NestedInteger list;\n while (in.peek() != ']') {\n list.add(deserialize(in));\n if (in.peek() == ',')\n in.get();\n }\n in.get();\n return list;\n }\n};\n``` | 78 | 0 | ['Recursion', 'Python', 'C++'] | 10 |
mini-parser | C++ Non-Recursive One-Pass Solution (using Stack) || A Possible Implementation of NestedInteger | c-non-recursive-one-pass-solution-using-mcdxv | Solution in a Glance:\nThis solution uses a stack to record the NestedInteger's.\nAt the very beginning, an empty NestedInteger is placed in the stack. This Nes | zhiqing_xiao | NORMAL | 2016-08-20T15:46:50.347000+00:00 | 2018-09-28T18:48:40.865593+00:00 | 7,539 | false | **Solution in a Glance:**\nThis solution uses a stack to record the NestedInteger's.\nAt the very beginning, an empty NestedInteger is placed in the stack. This NestedInteger will be regarded as a list that holds one but only one NestedInteger, which will be returned in the end.\n*Logic:* When encountering '[', the stack has one more element. When encountering ']', the stack has one less element.\n\n**Complexities:**\n* Time: *O*(n) \n* Space: worse-case *O*(n) (worse case: [1,[2,[3,[....[n-1,[n]]]....])\n\n**C++ Accepted Code:** \n(A possible implementation of **NestedInteger** is also provided in the first reply.)\n\n class Solution {\n public:\n NestedInteger deserialize(string s) {\n function<bool(char)> isnumber = [](char c){ return (c == '-') || isdigit(c); };\n \n stack<NestedInteger> stk;\n stk.push(NestedInteger());\n \n for (auto it = s.begin(); it != s.end();) {\n const char & c = (*it);\n if (isnumber(c)) {\n auto it2 = find_if_not(it, s.end(), isnumber);\n int val = stoi(string(it, it2));\n stk.top().add(NestedInteger(val));\n it = it2;\n }\n else {\n if (c == '[') {\n stk.push(NestedInteger());\n }\n else if (c == ']') {\n NestedInteger ni = stk.top();\n stk.pop();\n stk.top().add(ni);\n }\n ++it;\n }\n }\n \n NestedInteger result = stk.top().getList().front();\n return result;\n }\n }; | 54 | 0 | ['C'] | 7 |
mini-parser | Python O(N) one pass iterative solution | python-on-one-pass-iterative-solution-by-ah5a | \nclass Solution:\n def deserialize(self, s):\n stack, num, last = [], "", None\n for c in s:\n if c.isdigit() or c == "-": num += c | cenkay | NORMAL | 2018-08-03T14:57:04.245763+00:00 | 2018-10-06T06:52:27.703773+00:00 | 2,638 | false | ```\nclass Solution:\n def deserialize(self, s):\n stack, num, last = [], "", None\n for c in s:\n if c.isdigit() or c == "-": num += c\n elif c == "," and num:\n stack[-1].add(NestedInteger(int(num)))\n num = ""\n elif c == "[":\n elem = NestedInteger()\n if stack: stack[-1].add(elem)\n stack.append(elem)\n elif c == "]":\n if num:\n stack[-1].add(NestedInteger(int(num)))\n num = ""\n last = stack.pop()\n return last if last else NestedInteger(int(num))\n``` | 42 | 1 | [] | 1 |
mini-parser | A top down parser using c++ | a-top-down-parser-using-c-by-moevery-sq08 | c++\nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n int index = 0;\n char c = s[index];\n if (c == '[') {\n | moevery | NORMAL | 2016-08-14T14:43:03.076000+00:00 | 2016-08-14T14:43:03.076000+00:00 | 4,766 | false | ```c++\nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n int index = 0;\n char c = s[index];\n if (c == '[') {\n return parseList(s, index);\n } else {\n // starts with 0-9, '-'\n return parseNumber(s, index);\n }\n }\n \n NestedInteger parseList(string &s, int &index) {\n index++; // eat '['\n NestedInteger root;\n while (index < s.size()) {\n char c = s[index];\n if (c == '[') {\n root.add(parseList(s, index));\n } else if (isNumber(c) || c == '-') {\n root.add(parseNumber(s, index));\n } else if (c == ',') {\n // skip\n index++;\n } else if (c == ']') {\n break;\n }\n }\n index++; // eat ']'\n return root;\n }\n \n NestedInteger parseNumber(string &s, int &index) {\n int n = 0;\n int positive = 1; // flag for positive number\n if (s[index] == '-') {\n positive = -1;\n index++;\n }\n while (index < s.size()) {\n char c = s[index];\n if (isNumber(c)) {\n n = 10 * n + c - '0';\n index++;\n } else {\n break;\n }\n }\n return NestedInteger(n * positive);\n }\n \n bool isNumber(char c) {\n return '0' <= c && c <= '9';\n }\n};\n``` | 37 | 1 | [] | 2 |
mini-parser | Short Java recursive solution | short-java-recursive-solution-by-mylzsd-1a62 | \n\npublic class Solution {\n public NestedInteger deserialize(String s) {\n NestedInteger ret = new NestedInteger();\n if (s == null || s.leng | mylzsd | NORMAL | 2016-08-14T19:39:09.151000+00:00 | 2018-10-06T01:41:25.067063+00:00 | 5,898 | false | \n```\npublic class Solution {\n public NestedInteger deserialize(String s) {\n NestedInteger ret = new NestedInteger();\n if (s == null || s.length() == 0) return ret;\n if (s.charAt(0) != '[') {\n ret.setInteger(Integer.parseInt(s));\n }\n else if (s.length() > 2) {\n int start = 1, count = 0;\n for (int i = 1; i < s.length(); i++) {\n char c = s.charAt(i);\n if (count == 0 && (c == ',' || i == s.length() - 1)) {\n ret.add(deserialize(s.substring(start, i)));\n start = i + 1;\n }\n else if (c == '[') count++;\n else if (c == ']') count--;\n }\n }\n return ret;\n }\n}\n``` | 32 | 1 | [] | 2 |
mini-parser | Java Solution using Stack. logic same same as basic calculator question | java-solution-using-stack-logic-same-sam-vovi | \n public NestedInteger deserialize(String s) {\n if(s == null || s.isEmpty()) return new NestedInteger();\n Stack<NestedInteger> stack = new S | vvv_vvv | NORMAL | 2016-08-15T15:53:34.819000+00:00 | 2018-08-27T21:00:04.823329+00:00 | 2,120 | false | ```\n public NestedInteger deserialize(String s) {\n if(s == null || s.isEmpty()) return new NestedInteger();\n Stack<NestedInteger> stack = new Stack<>();\n int sign = 1, len = s.length() ;\n for(int i = 0 ; i < len ; i++){\n char c = s.charAt(i);\n if(c == '['){\n stack.push(new NestedInteger()); // start of a new NestedInteger\n }else if( c == ']' && stack.size() > 1){ // End of a NesterdInteger\n NestedInteger n = stack.pop();\n stack.peek().add(n); \n }else if(c == '-'){ // just change the sign \n sign = -1;\n }else if(Character.isDigit(c)){ // if digit check for all the continous ones\n int num = c - '0';\n while( i + 1 < len && Character.isDigit(s.charAt(i+1))){\n num = num * 10 + s.charAt(i+1) - '0';\n i++;\n }\n num = num * sign;\n if(!stack.isEmpty()){\n stack.peek().add(new NestedInteger(num)); // add to previous item if not empty\n }else{\n stack.push(new NestedInteger(num));\n }\n sign = 1; // reset the sign\n }\n }\n return stack.isEmpty() ? new NestedInteger() : stack.pop() ; \n }\n``` | 24 | 0 | [] | 4 |
mini-parser | Straightforward Java solution with explanation and a simple implementation of NestedInteger for your ease of testing | straightforward-java-solution-with-expla-97ka | Also viewable here.\n\nThe idea is very straightforward:\n\n1. if it's '[', we just construct a new nested integer and push it onto the stack\n\n2. if it's a nu | fishercoder | NORMAL | 2016-08-14T18:21:09.775000+00:00 | 2016-08-14T18:21:09.775000+00:00 | 5,912 | false | Also viewable [here](https://github.com/fishercoder1534/Leetcode/blob/master/src/main/java/com/fishercoder/solutions/MiniParser.java).\n\nThe idea is very straightforward:\n\n1. if it's '[', we just construct a new nested integer and push it onto the stack\n\n2. if it's a number, we parse the whole number and add to the previous nested integer object\n\n3. if it's ',', we'll just continue;\n\n4. if it's ']', we'll just pop one nested integer from the working stack and assign it to the result\n\nAlso, we'll pay attention to this corner case or understand the input: the input could be "324", "[324]", they are different: the former should return a nested integer with one single integer, the latter should return a nested integer with a list\n```\npublic NestedInteger deserialize(String s) {\n if(s == null || s.isEmpty() || s.length() == 0) return new NestedInteger();\n Stack<NestedInteger> workStack = new Stack<NestedInteger>();\n NestedInteger result = null;\n StringBuilder sb = new StringBuilder();\n int i = 0;\n //if it's just a single number, then we'll just return a nested integer with one integer\n if(s.charAt(i) != '['){\n sb.setLength(0);\n while(i < s.length() && ((Character.getNumericValue(s.charAt(i)) < 10 && Character.getNumericValue(s.charAt(i)) >= 0) || s.charAt(i) == '-')){\n sb.append(s.charAt(i));\n i++;\n }\n int num = Integer.parseInt(sb.toString());\n return new NestedInteger(num);\n }//all other cases, we'll return a nested integer with a list\n else{\n while (i < s.length()) {\n if (s.charAt(i) == '[') {\n NestedInteger ni = new NestedInteger();\n // we'll put this one into its last one if there's one on the workStack\n if (!workStack.isEmpty()) {\n NestedInteger lastNi = workStack.pop();\n lastNi.add(ni);\n workStack.push(lastNi);// then push it back\n }\n workStack.push(ni);\n i++;\n } else if (s.charAt(i) == ',') {\n i++;\n } else if (s.charAt(i) == ']') {\n NestedInteger completedNi = workStack.pop();\n result = completedNi;\n i++;\n } else {\n // then it must be a number\n sb.setLength(0);\n while (i < s.length()\n && ((Character.getNumericValue(s.charAt(i)) < 10 && Character\n .getNumericValue(s.charAt(i)) >= 0) || s.charAt(i) == '-')) {\n sb.append(s.charAt(i));\n i++;\n }\n int num = Integer.parseInt(sb.toString());\n NestedInteger ni = null;\n if (!workStack.isEmpty())\n ni = workStack.pop();\n else\n ni = new NestedInteger();\n // case 1: if this one contains one integer\n if (ni.isInteger()) {\n // we'll add it to this ni\n ni.add(new NestedInteger(num));\n }\n // case 2: if this one contains a nested integer\n else if (ni.getList() != null && ni.getList().size() != 0) {\n // we'll get the last nested integer and add this one to it\n ni.add(new NestedInteger(num));\n } else {\n // case 3: if this is an empty nested integer\n if(i > 0) ni.add(new NestedInteger(num));\n else ni.setInteger(num);\n }\n workStack.push(ni);\n if (i == s.length())\n return ni;// this is for test cases like this: "324", there's no '[' or ']'\n }\n }\n }\n return result;\n }\n```\n\nAlso, I've written a simple implementation for NestedInteger class, I find it helpful, posted it here as well:\n```\nclass NestedInteger {\n private List<NestedInteger> list;\n private Integer integer;\n \n public NestedInteger(List<NestedInteger> list){\n this.list = list;\n }\n \n public void add(NestedInteger nestedInteger) {\n if(this.list != null){\n this.list.add(nestedInteger);\n } else {\n this.list = new ArrayList();\n this.list.add(nestedInteger);\n }\n }\n\n public void setInteger(int num) {\n this.integer = num;\n }\n\n public NestedInteger(Integer integer){\n this.integer = integer;\n }\n\n public NestedInteger() {\n this.list = new ArrayList();\n }\n\n public boolean isInteger() {\n return integer != null;\n }\n\n public Integer getInteger() {\n return integer;\n }\n\n public List<NestedInteger> getList() {\n return list;\n }\n \n public String printNi(NestedInteger thisNi, StringBuilder sb){\n if(thisNi.isInteger()) {\n sb.append(thisNi.integer);\n sb.append(",");\n }\n sb.append("[");\n for(NestedInteger ni : thisNi.list){\n if(ni.isInteger()) {\n sb.append(ni.integer);\n sb.append(",");\n }\n else {\n printNi(ni, sb);\n }\n }\n sb.append("]");\n return sb.toString();\n }\n}\n\n``` | 18 | 1 | [] | 1 |
mini-parser | 385: Time 92.59% and Space 97.53%, Solution with step by step explanation | 385-time-9259-and-space-9753-solution-wi-akwi | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. We start by checking if the input string s starts with a [. If it does | Marlen09 | NORMAL | 2023-03-04T06:48:00.537340+00:00 | 2023-03-04T06:48:00.537396+00:00 | 1,783 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We start by checking if the input string s starts with a [. If it doesn\'t, then it must be a single integer, so we create a NestedInteger object with that value and return it.\n\n```\nif s[0] != \'[\':\n return NestedInteger(int(s))\n```\n2. If the input string does start with a [, we create an empty stack to keep track of NestedInteger objects and sublists as we parse the input string.\n```\nstack = []\n```\n3. We then loop through each character in the input string, using enumerate to keep track of the index of the current character.\n```\nfor i, c in enumerate(s):\n```\n4. If we encounter an opening bracket [, we push a new empty NestedInteger object onto the stack and set the starting index for the next element to be parsed.\n```\nif c == \'[\':\n stack.append(NestedInteger())\n start = i + 1\n```\n5. If we encounter a comma ,, we check if there was a number between the previous comma or opening bracket and this one. If there was, we create a new NestedInteger object with that value and add it to the NestedInteger object on the top of the stack. We then update the starting index for the next element to be parsed.\n```\nelif c == \',\':\n if i > start:\n num = int(s[start:i])\n stack[-1].add(NestedInteger(num))\n start = i + 1\n```\n6. If we encounter a closing bracket ], we pop the top NestedInteger object from the stack and check if there was a number between the previous comma or opening bracket and this one. If there was, we create a new NestedInteger object with that value and add it to the popped NestedInteger object. If there are still NestedInteger objects on the stack, we add the popped NestedInteger to the one on top. Otherwise, we return the popped NestedInteger. We then update the starting index for the next element to be parsed.\n\n```\nelif c == \']\':\n popped = stack.pop()\n if i > start:\n num = int(s[start:i])\n popped.add(NestedInteger(num))\n if stack:\n stack[-1].add(popped)\n else:\n return popped\n start = i + 1\n```\n7. After the loop is finished, we should have only one NestedInteger object left on the stack. We return this object as the final deserialized result.\n```\nreturn stack[-1]\n```\n# Complexity\n- Time complexity:\n92.59%\n\n- Space complexity:\n97.53%\n\n# Code\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n # If s doesn\'t start with a \'[\', it must be a single integer, so create a NestedInteger object with that value\n if s[0] != \'[\':\n return NestedInteger(int(s))\n\n # Create an empty stack to keep track of NestedInteger objects and sublists as we parse the input string\n stack = []\n\n # Loop through each character in the string\n for i, c in enumerate(s):\n if c == \'[\':\n # If we encounter an opening bracket, push a new empty NestedInteger object onto the stack and set the starting index for the next element\n stack.append(NestedInteger())\n start = i + 1\n elif c == \',\':\n # If we encounter a comma, check if there was a number between the previous comma or opening bracket and this one.\n # If there was, create a new NestedInteger object with that value and add it to the NestedInteger object on the top of the stack\n if i > start:\n num = int(s[start:i])\n stack[-1].add(NestedInteger(num))\n # Update the starting index for the next element to be parsed\n start = i + 1\n elif c == \']\':\n # If we encounter a closing bracket, pop the top NestedInteger object from the stack and check if there was a number between the previous comma or opening bracket and this one.\n # If there was, create a new NestedInteger object with that value and add it to the popped NestedInteger object\n popped = stack.pop()\n if i > start:\n num = int(s[start:i])\n popped.add(NestedInteger(num))\n # If there are still NestedInteger objects on the stack, add the popped NestedInteger to the one on top. Otherwise, return the popped NestedInteger\n if stack:\n stack[-1].add(popped)\n else:\n return popped\n # Update the starting index for the next element to be parsed\n start = i + 1\n\n``` | 14 | 0 | ['String', 'Stack', 'Depth-First Search', 'Python', 'Python3'] | 2 |
mini-parser | Very short recursive solution | very-short-recursive-solution-by-quesder-a6al | ```\nclass Solution {\npublic: \n NestedInteger parse(string& s, int& i) {\n if(s[i]=='[') {\n ++i;\n NestedInteger list;\n | quesder | NORMAL | 2016-08-28T04:15:14.402000+00:00 | 2016-08-28T04:15:14.402000+00:00 | 1,401 | false | ```\nclass Solution {\npublic: \n NestedInteger parse(string& s, int& i) {\n if(s[i]=='[') {\n ++i;\n NestedInteger list;\n while(s[i] != ']') {\n list.add(parse(s,i));\n if(s[i] ==',') ++i;\n }\n ++i;\n return list;\n } else { \n int sum = 0;\n int sign=1;\n if(s[i] == '-'){ sign = -1; ++i;}\n while(isdigit(s[i])) { sum *= 10; sum+= s[i]-'0'; ++i;}\n return NestedInteger(sum*sign);\n }\n }\n NestedInteger deserialize(string s) {\n int i = 0;\n return parse(s, i);\n }\n}; | 14 | 0 | [] | 1 |
mini-parser | Python iterative solution with stack and dummy NestedInteger | python-iterative-solution-with-stack-and-v6sb | from collections import deque\n\n class Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: | asdfasdf | NORMAL | 2016-08-14T14:52:24.794000+00:00 | 2018-09-06T14:42:45.920725+00:00 | 2,289 | false | from collections import deque\n\n class Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n initial = NestedInteger()\n q = deque()\n q.append(initial)\n i = 0\n\n while(i < len(s)):\n if s[i] == '[':\n n = NestedInteger()\n q[-1].add(n)\n q.append(n)\n i += 1\n elif s[i] == ']':\n q.pop()\n i += 1\n elif s[i] == ',':\n i += 1\n else:\n j = i\n while j < len(s) and ('0' <= s[j] <= '9' or s[j] == '-'):\n j += 1\n q[-1].add(int(s[i:j]))\n i = j\n\n return q[0].getList()[0] | 13 | 0 | [] | 3 |
mini-parser | C++ Clean and Elegant Code with Clear logic | c-clean-and-elegant-code-with-clear-logi-7jaq | ```cs\nclass Solution {\n NestedInteger parse(const string &s, int & pos)\n {\n if (s[pos] == '[')\n return parseList(s, pos);\n | fentoyal | NORMAL | 2016-08-27T18:29:49.720000+00:00 | 2016-08-27T18:29:49.720000+00:00 | 2,208 | false | ```cs\nclass Solution {\n NestedInteger parse(const string &s, int & pos)\n {\n if (s[pos] == '[')\n return parseList(s, pos);\n return parseNum(s, pos);\n }\n NestedInteger parseNum(const string &s, int & pos)\n {\n int num = 0;\n int sign = s[pos] == '-' ? -1 : 1;\n if (s[pos] == '-' || s[pos] == '+')\n pos ++;\n for (;pos < s.size() && isdigit(s[pos]); pos ++)\n num = num * 10 + s[pos] - '0';\n return NestedInteger(sign * num);\n }\n NestedInteger parseList(const string &s, int &pos)\n {\n NestedInteger ni;\n while (s[pos] != ']')\n {\n pos ++; //skip [ or ,\n if (s[pos] == ']') break; //handle [] or [1,2,]\n ni.add(parse(s, pos));\n }\n pos ++; // skip ]\n return ni;\n }\npublic:\n NestedInteger deserialize(const string &s) {\n int pos = 0;//pos ALWAYS points to 1 position past the last parsed string;\n //This is an invariance maintained across the entire program.\n return parse(s, pos);\n }\n}; | 12 | 0 | ['C'] | 1 |
mini-parser | Python | Recursion | 1 Pass | Simplest Solution | python-recursion-1-pass-simplest-solutio-mit6 | \nclass Solution:\n def parseNumber(self, s, idx, isNegative=False):\n num = 0\n while idx < len(s) and s[idx].isdigit():\n num = nu | akash3anup | NORMAL | 2022-05-17T09:11:39.441239+00:00 | 2022-05-17T09:16:00.687722+00:00 | 691 | false | ```\nclass Solution:\n def parseNumber(self, s, idx, isNegative=False):\n num = 0\n while idx < len(s) and s[idx].isdigit():\n num = num*10 + int(s[idx])\n idx += 1\n if isNegative:\n num = -num\n return NestedInteger(num), idx\n \n def parseList(self, s, idx):\n obj = NestedInteger()\n while idx < len(s) and s[idx] != \']\':\n if s[idx].isdigit():\n data, idx = self.parseNumber(s, idx)\n obj.add(data)\n elif s[idx] == \'-\':\n data, idx = self.parseNumber(s, idx+1, True)\n obj.add(data)\n elif s[idx] == \'[\':\n data, idx = self.parseList(s, idx+1)\n obj.add(data)\n else:\n idx += 1\n\n return obj, idx+1\n \n def deserialize(self, s: str) -> NestedInteger:\n if s[0] != \'[\':\n if s[0] == \'-\':\n nestedInteger, _ = self.parseNumber(s, 1, True)\n else:\n nestedInteger, _ = self.parseNumber(s, 0)\n else:\n nestedInteger, _ = self.parseList(s, 1) \n\n return nestedInteger\n```\n\n***If you liked the above solution then please upvote!*** | 8 | 0 | ['Recursion', 'Python'] | 1 |
mini-parser | Short and Clean Java Recursive Solution with Explanation | short-and-clean-java-recursive-solution-i5g4c | Using the "lvl" variable to track if we are inside an inner integer.\nUsing lIndex to track the leftmost start position.\nEvery time the program hit the "[" inc | lzmshiwo | NORMAL | 2016-09-15T23:06:41.897000+00:00 | 2016-09-15T23:06:41.897000+00:00 | 1,376 | false | Using the "lvl" variable to track if we are inside an inner integer.\nUsing lIndex to track the leftmost start position.\nEvery time the program hit the "[" increase lvl, and decrease lvl when hit "]"\nWhen the program meets ","\n If lvl != 0, ignore the "," since we are inside a nested integer\n else do recursive call ,add the result to the current list and move lIndex.\n\n[ [abc, [xy]] , def, [qqq] ]\nni.add(myDeserialize("[abc, [xy]]"));\nni.add(myDeserialize("def");\nni.add(myDeserialize("[qqq]");\n\n\n\n public NestedInteger deserialize(String s) {\n if (s.length() == 0) return new NestedInteger();\n return myDeserialize(s, 0, s.length()-1);\n }\n \n private NestedInteger myDeserialize(String s, int start, int end) {\n if (s.charAt(start) != '[') \n return new NestedInteger(Integer.valueOf(s.substring(start, end+1)));\n\n NestedInteger ni = new NestedInteger();\n int lvl = 0, lIndex = start+1;\n \n for (int i=start+1 ; i<=end-1 ; ++i) {\n char ch = s.charAt(i);\n if (ch == '[') ++lvl;\n else if (ch == ']') --lvl; \n else if (ch == ',' && lvl == 0) {\n ni.add(myDeserialize(s, lIndex, i-1));\n lIndex = i + 1;\n }\n }\n if (lIndex <= end-1) {\n ni.add(myDeserialize(s, lIndex, end-1));\n }\n return ni; \n } | 8 | 0 | [] | 1 |
mini-parser | Python | 8 lines of code, built-in json parser. | python-8-lines-of-code-built-in-json-par-h0rk | Formal background.\n\nThe language we have to parse isn\'t regular (https://en.wikipedia.org/wiki/Regular_language), so we can\'t use a regex. Rather, the langu | float4 | NORMAL | 2021-11-14T21:41:08.314104+00:00 | 2021-11-14T21:41:08.314141+00:00 | 1,088 | false | # Formal background.\n\nThe language we have to parse isn\'t regular (https://en.wikipedia.org/wiki/Regular_language), so we can\'t use a regex. Rather, the language is context-free (https://en.wikipedia.org/wiki/Context-free_language). As we don\'t have access to a Context-Free Grammar parser module in python, we would have to parse the string ourselves using a while loop, which is a boring and tedious task that usually yields ugly code no matter how hard you try. Luckily, we can cheat our way out of this: we can use python\'s built-in json parser, because the grammar we have to parse is a subset of json :). As json is an LL(1) grammar (https://en.wikipedia.org/wiki/LL_parser), it can be parsed in linear time and space, which is great. I don\'t know with absolute certainty that Python\'s built-in json parser actually runs in linear time and space, but it would be very strange if that weren\'t the case.\n# Code\n\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n def toNI(xs) -> NestedInteger:\n # Case where xs is a single integer.\n if isinstance(xs, int):\n return NestedInteger(xs)\n # Case where xs is a list of integers and/or lists.\n assert(isinstance(xs, list))\n n = NestedInteger()\n for x in xs:\n # For every element in the list, convert it to a NestedInteger\n # and add it to `n`.\n n.add(toNI(x))\n return n\n\t\t\t\n return toNI(json.loads(s))\n```\n\n# Explanation of code\n\n`json.loads` parses the string and returns a python object. As we\'re parsing lists and ints here, `json.loads` will return an object that is either an int, or a list that contains 1 or more ints/lists. We can therefore convert the object returned by `json.loads` to a `NestedInteger` very easily, by using a small recursive function that uses some type checking to know whether we are dealing with an int or list at any given time.\n\n# Complexity\n\nAs json is an LL(1) grammar (https://en.wikipedia.org/wiki/LL_parser), it can be parsed in `O(n)` time and space. Our `toNI` function evaluates every int/list exactly once, and therefore also takes `O(n)` time and space.\n\nAll in all, comments and assertions excluded, this solution is 8 LOC and super easy to write. Top 93% speed, top 74% memory. | 6 | 1 | ['Python'] | 0 |
mini-parser | Simple Java Solution (Beats 98%) | simple-java-solution-beats-98-by-fabrizi-q3m6 | Basic idea:\nThe Nested Integer is composed an Integer or a List;\n\n- If it is a List (starts with [), then for each element of the list, (Integer or nested Li | fabrizio3 | NORMAL | 2016-12-10T12:35:41.125000+00:00 | 2016-12-10T12:35:41.125000+00:00 | 1,459 | false | Basic idea:\nThe Nested Integer is composed an Integer or a List;\n\n- If it is a List (starts with `[`), then for each element of the list, (Integer or nested List) call `deserialize()` and add the result of `deserialize()` to the current NestedInteger.\n- If it is an Integer, just add it as Nested Integer with single value\n\nFor example for the input string `"[123,456,[788,799,833],[[]],10,[]]"` the elements to be processed with `deserialize()` will be:\n```\ndeserialize("[123,456,[788,799,833],[[]],10,[]]")\n deserialize("123")\n deserialize("456")\n deserialize("[788,799,833]")\n deserialize("788")\n deserialize("799")\n deserialize("833")\n deserialize("[[]]")\n deserialize("[]")\n deserialize("10")\n deserialize("[]")\n```\nHere is the code implementing this idea:\n```\npublic NestedInteger deserialize(String s) {\n\tif(s.length()==0 || s.equals("[]")) return new NestedInteger();\n\tNestedInteger ni = new NestedInteger();\n\tchar[] chars = s.toCharArray();\n\tif(chars[0]=='[') {\n\t\tint elementStart = 1;\n\t\twhile(elementStart<chars.length) {\n\t\t\tint elementEnd = searchForElementEnd(chars,elementStart);\n\t\t\tString nextListElement = new String(chars,elementStart,elementEnd-elementStart);\n\t\t\tni.add(deserialize(nextListElement));\n\t\t\telementStart=elementEnd+1;\n\t\t}\n\t} else ni.setInteger(new Integer(new String(chars)));\n\treturn ni;\n}\n\nprivate int searchForElementEnd(char[] chars, int elementStart) {\n\tint countBrackets = 0;\n\tint i=elementStart;\n\tif(chars[i++]=='[') countBrackets++;\n\twhile(i<chars.length) {\n\t\tchar nextChar = chars[i];\n\t\tif(nextChar==']') {\n\t\t\tcountBrackets--;\n\t\t\tif(countBrackets<=0) {\n\t\t\t\tif(countBrackets==0) i++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if(nextChar=='[') countBrackets++;\n\t\telse if(nextChar==',' && countBrackets==0) {\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\treturn i;\n}\n```\n\n | 6 | 0 | ['Recursion', 'Java'] | 0 |
mini-parser | Easy Python recursive solution and stack solution, please be careful about time complexity | easy-python-recursive-solution-and-stack-uhuk | \nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n if s[0] != '[': | pushazhiniao | NORMAL | 2016-08-14T17:06:25.075000+00:00 | 2018-09-24T07:31:28.391392+00:00 | 1,519 | false | ```\nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n if s[0] != '[':\n return NestedInteger(int(s))\n nested = NestedInteger()\n numP, start = 0, 1\n for i in range(1, len(s)):\n if (numP == 0 and s[i] == ',') or i == len(s) - 1:\n # make sure it is not an empty string\n if start < i:\n nested.add(self.deserialize(s[start:i]))\n start = i + 1\n elif s[i] == '[':\n numP += 1\n elif s[i] == ']':\n numP -= 1\n return nested\n```\nI was a bit confused by add() and setInteger() both for adding integer element. I think add() can do what setInteger does.\n\n\nPlease note that this is not a very fast solution since it requires scanning elements multiple times according to this element's depth.\n\nUsing stack would use space as a trade-off for multiple scanning.\n\nMy stack solution, as many people have similar solutions:\n```\nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n stack, start = [], -1\n for i, c in enumerate(s):\n if c == '[':\n stack.append(NestedInteger())\n elif c == ']':\n # for last ], it is possible that there is only one NestedInteger\n if len(stack) > 1:\n t = stack.pop()\n stack[-1].add(t)\n elif c.isdigit() or c == '-':\n if start == -1:\n start = i\n if i == len(s) - 1 or not s[i + 1].isdigit():\n if stack:\n stack[-1].add(NestedInteger(int(s[start:i + 1])))\n else:\n stack.append(NestedInteger(int(s[start:i + 1])))\n start = -1\n return stack.pop()\n``` | 5 | 0 | [] | 3 |
mini-parser | Python Solution just 6 lines || Easy to understand approach || Using eval | python-solution-just-6-lines-easy-to-und-ejnr | \nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n\t\t# eval("[1,2,3]") => [1,2,3] it\'ll convert string of list to list\n return s | mohitsatija | NORMAL | 2023-02-08T15:14:00.351525+00:00 | 2023-02-08T15:14:00.351562+00:00 | 958 | false | ```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n\t\t# eval("[1,2,3]") => [1,2,3] it\'ll convert string of list to list\n return self.find(eval(s))\n \n def find(self,s):\n\t\t# if our elment s is type of int we\'ll return new NestedInteger of that value\n if type(s) == type(1):\n return NestedInteger(s)\n\t\t\t\n\t\t# create a new object that will contain our elements of type NestedInteger\n n = NestedInteger()\n \n\t\tfor x in s:\n\t\t\t# traverse the list s and recursively find all nestedIntegers and add them in container n\n\t\t\t# recursion will handle multiple nested lists\n n.add(self.find(x))\n return n\n``` | 4 | 0 | ['Depth-First Search', 'Recursion', 'Python', 'Python3'] | 2 |
mini-parser | Java | 2 different Stack solutions | Explained! | java-2-different-stack-solutions-explain-gam6 | There are two ways we can make stack solution works and they work rather differently. The first way is slightly more optimal but they both run in O(n).\n1. Init | Student2091 | NORMAL | 2022-04-14T20:37:20.667624+00:00 | 2022-04-14T20:39:20.347975+00:00 | 849 | false | There are two ways we can make stack solution works and they work rather differently. The first way is slightly more optimal but they both run in O(n).\n1. Initialize a new NestedList at the start and set it to `cur`\n\n2. Everytime we encounter `\'[\'`, we push `cur` onto the stack and set `cur` to be a new NestedList\n\n3. Everytime we encounter `-` or a `digit`, we parse the number and add it as a NestedInteger to `cur`\n\n4. Everytime we encounter `\']\'`, we end the `cur` NestedList by adding it to the top NestedList on the stack and set `cur` to that top NestedList and pop it.\n\n5. In the end, we return the first NestedList in `cur` because we\'d created an empty NestedList at step 1.\n\nThis solution runs in 5ms.\n```Java\n public NestedInteger deserialize(String s) {\n Deque<NestedInteger> stack = new ArrayDeque<>();\n NestedInteger cur = new NestedInteger();\n for (int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if (ch == \'[\'){\n stack.push(cur);\n cur = new NestedInteger();\n }else if (ch == \'-\' || Character.isDigit(ch)){\n int j = i + 1;\n while(j < s.length() && Character.isDigit(s.charAt(j))){\n ++j;\n }\n cur.add(parse(i, j, s));\n i = j - 1;\n }else if (ch == \']\'){\n stack.peek().add(cur);\n cur = stack.pop();\n }\n }\n return cur.getList().get(0);\n }\n\n private NestedInteger parse(int lo, int hi, String s){\n return new NestedInteger(Integer.parseInt(s.substring(lo, hi)));\n }\n```\n\nSecond way to make stack work is this:\n1. Each time we encounter `\'[\'`, we push NestedInteger_MAX_Integer to the stack to note this is a start of some NestedList.\n\n2. Each time we encounter `-` or a `digit`, we parse the number and push it onto the stack as a NestedInteger.\n\n3. Each time we encounter `\']\'`, we create a new stack, pop of all the elements in the stack to that new stack until we are at a NestedInteger.MAX_INTEGER. Then we create a new NestedList and pop off all the elements in the new stack to that and store it back to the stack.\n\n4. In the end, we return the first element on the stack. There is no edge case like the first approach.\n\nThis runs run 7ms, which is slightly slower than the 1st approach above, because there are more popping and pushing operations.\n\n\n\n```Java\n Deque<NestedInteger> stack = new ArrayDeque<>();\n for (int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if (ch == \'[\'){\n stack.push(new NestedInteger(Integer.MAX_VALUE));\n }else if (ch == \'-\' || Character.isDigit(ch)){\n int j = i + 1;\n while(j < s.length() && Character.isDigit(s.charAt(j))){\n ++j;\n }\n stack.push(parse(i, j, s));\n i = j - 1;\n }else if (ch == \']\'){\n Deque<NestedInteger> save = new ArrayDeque<>();\n while(!stack.peek().isInteger() || Integer.MAX_VALUE != stack.peek().getInteger()){\n save.push(stack.pop());\n }\n stack.pop();\n NestedInteger cur = new NestedInteger();\n while(!save.isEmpty()){\n cur.add(save.pop());\n }\n stack.push(cur);\n }\n }\n return stack.peek();\n }\n\n private NestedInteger parse(int lo, int hi, String s){\n return new NestedInteger(Integer.parseInt(s.substring(lo, hi)));\n }\n```\n**Which approach do you like more? Comment below :)** | 4 | 0 | ['Stack', 'Java'] | 1 |
mini-parser | C++ Stack | Concise | c-stack-concise-by-chenzhiyin1988-dytj | \nNestedInteger deserialize(string s) {\n if(s[0] != \'[\') return NestedInteger(stoi(s));\n \n stack<NestedInteger> stk;\n string num = "";\n for(cha | chenzhiyin1988 | NORMAL | 2021-09-27T04:54:33.436809+00:00 | 2022-03-12T03:04:13.206946+00:00 | 184 | false | ```\nNestedInteger deserialize(string s) {\n if(s[0] != \'[\') return NestedInteger(stoi(s));\n \n stack<NestedInteger> stk;\n string num = "";\n for(char c: s) {\n if(c == \'[\') {\n stk.push(NestedInteger());\n }\n else if(c == \']\' || c == \',\') {\n if(num != "") {\n stk.top().add(NestedInteger(stoi(num)));\n num = "";\n }\n \n if(stk.size() >= 2 && c == \']\') {\n NestedInteger ni = stk.top(); stk.pop();\n stk.top().add(ni); \n }\n }\n else num.push_back(c);\n }\n \n return stk.top();\n}\n``` | 4 | 0 | [] | 1 |
mini-parser | very short java solution | very-short-java-solution-by-rayszhangqq-j983 | \n public NestedInteger deserialize(String s) {\n if (s.contains("[")) {\n NestedInteger ans=new NestedInteger();\n if (s.length | rayszhangqq | NORMAL | 2016-08-19T22:45:17.178000+00:00 | 2016-08-19T22:45:17.178000+00:00 | 1,219 | false | ```\n public NestedInteger deserialize(String s) {\n if (s.contains("[")) {\n NestedInteger ans=new NestedInteger();\n if (s.length()>2) {\n int begin=1;\n char[] cs=s.toCharArray();\n int count=0;\n for (int i = 1; i < s.length()-1; i++) {\n if (cs[i]==','&&count==0) {\n ans.add(deserialize(s.substring(begin,i)));\n begin=i+1;\n }\n if (cs[i]=='['||cs[i]==']') { //ascii code '['->91 ']'->93\n count+=(92-cs[i]);\n }\n }\n ans.add(deserialize(s.substring(begin,s.length()-1)));\n }\n return ans;\n }\n return new NestedInteger(Integer.valueOf(s));\n }\n}\n``` | 4 | 0 | [] | 1 |
mini-parser | Python recursive solution | python-recursive-solution-by-notebook-je0k | A python recursive solution:\nFirst, determine the type of parsing: two scenarios can be met:\n1. the first character of a given string is '[': to parse a list. | notebook | NORMAL | 2016-08-15T18:16:32.007000+00:00 | 2016-08-15T18:16:32.007000+00:00 | 578 | false | A python recursive solution:\nFirst, determine the type of parsing: two scenarios can be met:\n1. the first character of a given string is '[': to parse a list.\nWhenever '[' is met, start parsing a list and end when ']' is met.\n2. otherwise: to parse a simple integer.\nThe recursive function should return the parsed result and the ending index of the subproblem or equivalently the start index of the next parsing task.\n```\ndef deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n parsed, _ = self.helper(s, 0)\n return parsed\n\n def helper(self, s, ind):\n i = ind\n # scenario 1: to parse a nested list\n if s[i] == '[':\n parsed = NestedInteger()\n i += 1\n while i < len(s):\n if s[i] == ']':\n return parsed, i+1\n if s[i] == '[':\n nested, i = self.helper(s, i)\n parsed.add(nested)\n elif s[i] in '-0123456789':\n ele, i = self.helper(s, i)\n parsed.add(ele)\n # put this case at the bottom so that we don't need list all the spaces (e.g. space, tab) or comma separator\n else:\n i += 1\n # scenario 2: to parse an integer\n else:\n temp = i\n while temp < len(s) and s[temp] in '-0123456789':\n temp += 1\n return NestedInteger(int(s[i:temp])), temp\n``` | 4 | 0 | [] | 1 |
mini-parser | Solution By Dare2Solve | Detailed Explanation | Clean Code | solution-by-dare2solve-detailed-explanat-78qo | Explanation []\nauthorslog.com/blog/aw46KFc7BX\n\n# Code\n\ncpp []\n// Assuming the NestedInteger class is defined like this:\n// class NestedInteger {\n// publ | Dare2Solve | NORMAL | 2024-09-11T18:12:44.940996+00:00 | 2024-09-11T18:12:44.941046+00:00 | 709 | false | ```Explanation []\nauthorslog.com/blog/aw46KFc7BX\n```\n# Code\n\n```cpp []\n// Assuming the NestedInteger class is defined like this:\n// class NestedInteger {\n// public:\n// NestedInteger() {}; // Initializes an empty list\n// NestedInteger(int value) {}; // Initializes a single integer\n// bool isInteger() const; // Returns true if this NestedInteger holds a single integer\n// int getInteger() const; // Returns the single integer that this NestedInteger holds\n// void setInteger(int value); // Set this NestedInteger to hold a single integer\n// void add(const NestedInteger &ni); // Adds a NestedInteger element to this NestedInteger\n// const std::vector<NestedInteger> &getList() const; // Returns the nested list\n// };\n\nclass Solution {\npublic:\n NestedInteger deserialize(const std::string &s) {\n std::istringstream iss(s);\n return parse(iss);\n }\n\nprivate:\n NestedInteger parse(std::istringstream &iss) {\n if (iss.peek() == \'[\') {\n iss.get(); // Skip \'[\'\n NestedInteger ni;\n while (iss.peek() != \']\') {\n ni.add(parse(iss));\n if (iss.peek() == \',\') {\n iss.get(); // Skip \',\'\n }\n }\n iss.get(); // Skip \']\'\n return ni;\n } else {\n int num;\n iss >> num;\n return NestedInteger(num);\n }\n }\n};\n```\n\n```python []\n# Assuming NestedInteger class is already defined with the following methods:\n# - NestedInteger() initializes an empty nested list.\n# - NestedInteger(int value) initializes a single integer.\n# - void add(NestedInteger ni) adds a NestedInteger element to this NestedInteger.\n# - bool isInteger() returns true if this NestedInteger holds a single integer.\n# - int getInteger() returns the single integer that this NestedInteger holds, if it holds a single integer.\n# - List[NestedInteger] getList() returns the nested list that this NestedInteger holds, if it holds a nested list.\n\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n a = json.loads(s)\n return self.dfs(a)\n\n def dfs(self, input) -> NestedInteger:\n if isinstance(input, int):\n return NestedInteger(input)\n l = NestedInteger()\n for e in input:\n l.add(self.dfs(e))\n return l\n```\n\n```java []\n// Assuming NestedInteger class is already defined with the following methods:\n// - NestedInteger() initializes an empty nested list.\n// - NestedInteger(int value) initializes a single integer.\n// - void add(NestedInteger ni) adds a NestedInteger element to this NestedInteger.\n// - boolean isInteger() returns true if this NestedInteger holds a single integer.\n// - Integer getInteger() returns the single integer that this NestedInteger holds, if it holds a single integer.\n// - List<NestedInteger> getList() returns the nested list that this NestedInteger holds, if it holds a nested list.\n\npublic class Solution {\n public NestedInteger deserialize(String s) {\n Object parsed = parse(s);\n return dfs(parsed);\n }\n\n private Object parse(String s) {\n if (s.charAt(0) == \'[\') {\n List<Object> list = new ArrayList<>();\n int start = 1, depth = 0;\n for (int i = 1; i < s.length(); i++) {\n if (s.charAt(i) == \'[\') depth++;\n else if (s.charAt(i) == \']\') depth--;\n else if (s.charAt(i) == \',\' && depth == 0) {\n list.add(parse(s.substring(start, i)));\n start = i + 1;\n }\n }\n if (start < s.length() - 1) list.add(parse(s.substring(start, s.length() - 1)));\n return list;\n } else {\n return Integer.parseInt(s);\n }\n }\n\n private NestedInteger dfs(Object input) {\n if (input instanceof Integer) {\n return new NestedInteger((int) input);\n }\n NestedInteger ni = new NestedInteger();\n for (Object obj : (List<Object>) input) {\n ni.add(dfs(obj));\n }\n return ni;\n }\n}\n```\n\n```javascript []\n/**\n * @param {string} s\n * @return {NestedInteger}\n */\nconst deserialize = (s) => {\n let a = JSON.parse(s);\n return dfs(a);\n};\n\nconst dfs = (input) => {\n if (Number.isInteger(input)) return new NestedInteger(input); // if (!Array.isArray(input)) return new NestedInteger(input); also works\n let l = new NestedInteger();\n for (const e of input) l.add(dfs(e));\n return l;\n};\n``` | 3 | 0 | ['Stack', 'Depth-First Search', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
mini-parser | c++ |easy to understand | short | c-easy-to-understand-short-by-venomhighs-0o7c | \n# Code\n\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n | venomhighs7 | NORMAL | 2022-10-07T11:27:42.348043+00:00 | 2022-10-07T11:27:42.348077+00:00 | 1,222 | false | \n# Code\n```\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n * public:\n * // Constructor initializes an empty nested list.\n * NestedInteger();\n *\n * // Constructor initializes a single integer.\n * NestedInteger(int value);\n *\n * // Return true if this NestedInteger holds a single integer, rather than a nested list.\n * bool isInteger() const;\n *\n * // Return the single integer that this NestedInteger holds, if it holds a single integer\n * // The result is undefined if this NestedInteger holds a nested list\n * int getInteger() const;\n *\n * // Set this NestedInteger to hold a single integer.\n * void setInteger(int value);\n *\n * // Set this NestedInteger to hold a nested list and adds a nested integer to it.\n * void add(const NestedInteger &ni);\n *\n * // Return the nested list that this NestedInteger holds, if it holds a nested list\n * // The result is undefined if this NestedInteger holds a single integer\n * const vector<NestedInteger> &getList() const;\n * };\n */\nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n function<bool(char)> isnumber = [](char c){ return (c == \'-\') || isdigit(c); };\n \n stack<NestedInteger> stk;\n stk.push(NestedInteger());\n \n for (auto it = s.begin(); it != s.end();) {\n const char & c = (*it);\n if (isnumber(c)) {\n auto it2 = find_if_not(it, s.end(), isnumber);\n int val = stoi(string(it, it2));\n stk.top().add(NestedInteger(val));\n it = it2;\n }\n else {\n if (c == \'[\') {\n stk.push(NestedInteger());\n }\n else if (c == \']\') {\n NestedInteger ni = stk.top();\n stk.pop();\n stk.top().add(ni);\n }\n ++it;\n }\n }\n \n NestedInteger result = stk.top().getList().front();\n return result;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
mini-parser | Go 0ms | go-0ms-by-dynasty919-hhb2 | \nfunc deserialize(s string) *NestedInteger {\n \n stack := []*NestedInteger{}\n \n i := 0\n for i < len(s) {\n switch {\n case | dynasty919 | NORMAL | 2020-08-15T18:05:33.203318+00:00 | 2020-08-15T18:13:19.733650+00:00 | 108 | false | ```\nfunc deserialize(s string) *NestedInteger {\n \n stack := []*NestedInteger{}\n \n i := 0\n for i < len(s) {\n switch {\n case s[i] == \'[\':\n stack = append(stack, &NestedInteger{})\n \n case s[i] == \']\':\n if len(stack) == 1 {\n break\n } else {\n stack[len(stack) - 2].Add(*stack[len(stack) - 1])\n stack = stack[:len(stack) - 1]\n }\n \n case (s[i] >= \'0\' && s[i] <= \'9\') || s[i] == \'-\' :\n sign := 1\n if s[i] == \'-\' {\n sign = -1\n i++\n }\n \n num := 0\n for i < len(s) && s[i] >= \'0\' && s[i] <= \'9\'{\n num = num * 10 + int(s[i] - \'0\')\n i++\n }\n \n elem := &NestedInteger{}\n elem.SetInteger(sign * num)\n \n if len(stack) == 0 {\n return elem\n }\n stack[len(stack) - 1].Add(*elem)\n i--\n }\n i++\n }\n \n return stack[0]\n}\n``` | 3 | 0 | [] | 0 |
mini-parser | Recursive solution but clean and simple code in C | recursive-solution-but-clean-and-simple-hddpu | \nstruct NestedInteger* deserializeUtil(char** s) {\n struct NestedInteger *ni = NestedIntegerInit(), *num_ni = NULL;\n char *end = NULL;\n \n if(** | brickell | NORMAL | 2018-02-10T07:54:32.412000+00:00 | 2018-02-10T07:54:32.412000+00:00 | 222 | false | ```\nstruct NestedInteger* deserializeUtil(char** s) {\n struct NestedInteger *ni = NestedIntegerInit(), *num_ni = NULL;\n char *end = NULL;\n \n if(**s != '['){\n NestedIntegerSetInteger(ni, strtoul(*s, NULL, 0));\n return ni;\n }\n \n if(**s == '[') (*s)++;\n \n while(**s != ']'){\n if(**s == ',') (*s)++;\n else if(**s == '[') NestedIntegerAdd(ni, deserializeUtil(s));\n else {\n num_ni = NestedIntegerInit();\n NestedIntegerSetInteger(num_ni, strtol(*s, &end, 10));\n NestedIntegerAdd(ni, num_ni);\n *s = end;//http://en.cppreference.com/w/c/string/byte/strtol\n }\n }\n\n if(**s == ']') (*s)++;\n \n return ni;\n}\n\nstruct NestedInteger* deserialize(char* s) {\n return deserializeUtil(&s);\n}\n``` | 3 | 0 | [] | 0 |
mini-parser | Java iterative and recursive (including one-pass) solution | java-iterative-and-recursive-including-o-b8h5 | Both are straight forward.\n\n\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') return new NestedInteger(Integer.parseInt(s)); | iaming | NORMAL | 2016-08-17T00:38:39.388000+00:00 | 2018-08-21T22:01:29.947526+00:00 | 1,129 | false | Both are straight forward.\n\n```\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') return new NestedInteger(Integer.parseInt(s));\n NestedInteger cur = new NestedInteger();\n Stack<NestedInteger> stack = new Stack<>();\n for (int i = 1, start = 1; i < s.length(); ++i) {\n if (s.charAt(i) == '[') {\n stack.push(cur);\n cur = new NestedInteger();\n stack.peek().add(cur);\n start = i + 1;\n } else if (s.charAt(i) == ']' || s.charAt(i) == ',') {\n if (start < i) \n cur.add(new NestedInteger(Integer.parseInt(s.substring(start, i))));\n start = i + 1;\n if (s.charAt(i) == ']' && !stack.empty()) cur = stack.pop();\n }\n }\n return cur;\n }\n```\n```\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') return new NestedInteger(Integer.parseInt(s));\n NestedInteger ans = new NestedInteger();\n int prev = 1;\n for (int i = 1, cnt = 0; i < s.length() - 1; ++i) {\n if (s.charAt(i) == '[') {\n cnt++;\n } else if (s.charAt(i) == ']') {\n cnt--;\n } else if (s.charAt(i) == ',' && cnt == 0) {\n ans.add(deserialize(s.substring(prev, i)));\n prev = i + 1;\n }\n }\n if (prev < s.length() - 1) // not '[]'\n ans.add(deserialize(s.substring(prev, s.length() - 1)));\n return ans;\n }\n```\n\nOne pass recursive.\n\n```\n int idx;\n public NestedInteger deserialize(String s) {\n idx = 0;\n return helper(s);\n }\n NestedInteger helper(String s) {\n NestedInteger ans = new NestedInteger();\n if (s.charAt(idx) != '[') {\n int start = idx;\n while (idx < s.length() && s.charAt(idx) != ',' && s.charAt(idx) != ']') ++idx;\n ans.setInteger(Integer.parseInt(s.substring(start, idx--)));\n } else {\n for (++idx; idx < s.length() && s.charAt(idx) != ']'; ++idx)\n if (s.charAt(idx) != ',') ans.add(helper(s));\n }\n return ans;\n }\n``` | 3 | 0 | [] | 2 |
mini-parser | Clean Iterative Java Solution using Stack | clean-iterative-java-solution-using-stac-weyj | \npublic class Solution {\n public NestedInteger deserialize(String s) {\n String[] tokens = s.split(",");\n Stack<NestedInteger> stack = new S | wcyz666 | NORMAL | 2016-08-26T01:17:29.010000+00:00 | 2016-08-26T01:17:29.010000+00:00 | 477 | false | ```\npublic class Solution {\n public NestedInteger deserialize(String s) {\n String[] tokens = s.split(",");\n Stack<NestedInteger> stack = new Stack();\n NestedInteger root = new NestedInteger();\n stack.push(root);\n \n for (String token: tokens) {\n int start = 0;\n int end = token.length();\n \n while (token.charAt(start) == '[') {\n stack.push(new NestedInteger());\n start++;\n }\n \n NestedInteger topMost = stack.peek();\n \n while (token.charAt(end - 1) == ']') {\n NestedInteger prevList = stack.pop();\n stack.peek().add(prevList);\n end--;\n }\n \n if (start < end) {\n NestedInteger curInteger = new NestedInteger(Integer.parseInt(token.substring(start, end)));\n topMost.add(curInteger); \n }\n }\n \n return root.getList().get(0);\n }\n}\n``` | 3 | 0 | [] | 1 |
mini-parser | Recursive Python solution with explanation | recursive-python-solution-with-explanati-whpb | Intuition\nSplit the tokens and recursively process them.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. If the string does not | zerocores | NORMAL | 2024-02-15T14:32:03.597078+00:00 | 2024-02-15T14:32:03.597107+00:00 | 175 | false | # Intuition\nSplit the tokens and recursively process them.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. If the string does not start with `[`, it\'s a scalar.\n2. If it\'s a list, split the string into tokens(elements) and recursively process them.\n3. If there\'s a nested list, count `[` and `]`. Only process when these 2 numbers are equal.\n<!-- Describe your approach to solving the problem. -->\n\n# Code\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n return self._deserialize(s, 0, len(s) - 1)\n\n def _deserialize(self, s: str, i, j) -> NestedInteger:\n if s[i] != "[": # scalar\n return NestedInteger(int(s[i:j+1]))\n\n res = NestedInteger()\n if j == i + 1: # empty list\n return res\n\n start = idx = i + 1 # indices for elements\n count = 0 # count the brackets\n while idx <= j:\n if count == 0 and (s[idx] == "," or s[idx] == "]"): # end of 1 element\n res.add(self._deserialize(s, start, idx - 1)) # recursively parse the element\n start = idx + 1\n elif s[idx] == "[": # start of another nested list\n count += 1\n elif s[idx] == "]": # end of 1 nested list\n count -= 1\n idx += 1\n return res\n\n``` | 2 | 0 | ['Python3'] | 0 |
mini-parser | [Python] eval | python-eval-by-pbelskiy-6ahv | python\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n \n def dfs(obj):\n if isinstance(obj, int):\n | pbelskiy | NORMAL | 2023-11-22T20:22:39.501373+00:00 | 2023-11-22T20:22:39.501396+00:00 | 164 | false | ```python\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n \n def dfs(obj):\n if isinstance(obj, int):\n return NestedInteger(obj)\n\n ni = NestedInteger() \n for el in obj:\n if isinstance(el, list):\n ni.add(dfs(el))\n else:\n ni.add(NestedInteger(el))\n \n return ni\n\n return dfs(eval(s))\n``` | 2 | 0 | ['Depth-First Search', 'Python'] | 0 |
mini-parser | Mini Parser Solution Java | mini-parser-solution-java-by-bhupendra78-ykm3 | class Solution {\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != \'[\')\n return new NestedInteger(Integer.parseInt(s));\n\n Deq | bhupendra786 | NORMAL | 2022-09-17T09:46:32.023240+00:00 | 2022-09-17T09:46:32.023279+00:00 | 623 | false | class Solution {\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != \'[\')\n return new NestedInteger(Integer.parseInt(s));\n\n Deque<NestedInteger> stack = new ArrayDeque<>();\n int start = 1;\n\n for (int i = 0; i < s.length(); ++i)\n switch (s.charAt(i)) {\n case \'[\':\n stack.push(new NestedInteger());\n start = i + 1;\n break;\n case \',\':\n if (i > start) {\n final int num = Integer.parseInt(s.substring(start, i));\n stack.peek().add(new NestedInteger(num));\n }\n start = i + 1;\n break;\n case \']\':\n NestedInteger popped = stack.pop();\n if (i > start) {\n final int num = Integer.parseInt(s.substring(start, i));\n popped.add(new NestedInteger(num));\n }\n if (!stack.isEmpty())\n stack.peek().add(popped);\n else\n return popped;\n start = i + 1;\n break;\n }\n\n throw new IllegalArgumentException();\n }\n}\n | 2 | 0 | ['String', 'Stack', 'Depth-First Search'] | 0 |
mini-parser | javascript easy dfs 174ms | javascript-easy-dfs-174ms-by-henrychen22-6e3w | \nconst deserialize = (s) => {\n let a = JSON.parse(s);\n return dfs(a);\n};\n\nconst dfs = (input) => {\n if (Number.isInteger(input)) return new Nest | henrychen222 | NORMAL | 2022-02-08T18:50:36.613417+00:00 | 2022-02-08T18:52:26.318847+00:00 | 499 | false | ```\nconst deserialize = (s) => {\n let a = JSON.parse(s);\n return dfs(a);\n};\n\nconst dfs = (input) => {\n if (Number.isInteger(input)) return new NestedInteger(input); // if (!Array.isArray(input)) return new NestedInteger(input); also works\n let l = new NestedInteger();\n for (const e of input) l.add(dfs(e));\n return l;\n};\n``` | 2 | 0 | ['Depth-First Search', 'Recursion', 'JavaScript'] | 1 |
mini-parser | python recursive | python-recursive-by-hzhaoc-qqx7 | \nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n def search(i, s):\n res, j = NestedInteger(), i\n while i | hzhaoc | NORMAL | 2021-11-12T22:48:04.584560+00:00 | 2021-11-12T22:48:04.584587+00:00 | 94 | false | ```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n def search(i, s):\n res, j = NestedInteger(), i\n while i < len(s):\n if s[i].isdigit() or s[i] == \'-\':\n i += 1\n elif s[i] == \',\':\n if j < i:\n res.add(NestedInteger(int(s[j:i])))\n i += 1\n j = i\n elif s[i] == \'[\':\n _, i = search(i+1, s)\n res.add(_)\n i += 1\n j = i\n else: # \']\'\n if j < i:\n res.add(NestedInteger(int(s[j:i])))\n j = i\n return res, i\n if j < i:\n res.setInteger(int(s[j:i]))\n return res, i\n\n return search(s[0] == \'[\', s)[0]\n``` | 2 | 0 | [] | 0 |
mini-parser | Java | Stack | explanation | java-stack-explanation-by-qin10-7lzk | ```\nclass Solution {\n public NestedInteger deserialize(String s) {\n if(s.charAt(0) != \'[\') return new NestedInteger(Integer.parseInt(s));\n | qin10 | NORMAL | 2021-10-21T16:19:21.740462+00:00 | 2021-10-21T16:21:00.334839+00:00 | 178 | false | ```\nclass Solution {\n public NestedInteger deserialize(String s) {\n if(s.charAt(0) != \'[\') return new NestedInteger(Integer.parseInt(s));\n \n NestedInteger root = new NestedInteger();\n Deque<NestedInteger> stack = new ArrayDeque<NestedInteger>();\n stack.push(root);\n \n StringBuilder sb = new StringBuilder();\n NestedInteger curr;\n \n for(int i = 1; i < s.length(); ++i) {\n char c = s.charAt(i);\n \n if(c != \'[\' && c != \',\' && c != \']\') { //if digit, append to sb\n sb.append(c);\n continue;\n }\n \n if (c == \'[\') { // if \'[\' -- 1. create new list and add it to previous list. 2. add this new list to stack.\n NestedInteger child = new NestedInteger();\n stack.peek().add(child);\n stack.push(child);\n } else if(c == \']\' || c == \',\') { // if \']\' or \',\' -- add sb to current list\n if(sb.length() != 0) { // skip if empty sb\n curr = new NestedInteger(Integer.parseInt(sb.toString()));\n stack.peek().add(curr);\n }\n \n if(c == \']\') stack.pop(); // \']\' means end of current list. pop it from queue.\n }\n\t\t\t\t\n sb.setLength(0); // clear current sb\n }\n return root;\n }\n} | 2 | 0 | [] | 0 |
mini-parser | [Python3] a concise recursive solution | python3-a-concise-recursive-solution-by-qjsrf | \n\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if not s: return NestedInteger()\n if not s.startswith("["): return Nes | ye15 | NORMAL | 2020-10-02T21:09:21.783483+00:00 | 2020-10-02T21:09:21.783514+00:00 | 410 | false | \n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if not s: return NestedInteger()\n if not s.startswith("["): return NestedInteger(int(s)) # integer \n ans = NestedInteger()\n s = s[1:-1] # strip outer "[" and "]"\n if s: \n ii = op = 0 \n for i in range(len(s)): \n if s[i] == "[": op += 1\n if s[i] == "]": op -= 1\n if s[i] == "," and op == 0: \n ans.add(self.deserialize(s[ii:i]))\n ii = i+1\n ans.add(self.deserialize(s[ii:i+1]))\n return ans \n``` | 2 | 0 | ['Python3'] | 0 |
mini-parser | Java stack solution easy to understand | java-stack-solution-easy-to-understand-b-t5pz | 1 Everything will be pushed to stack, so no extra pointers or references needed (will get messy if there are many pointers)\n2 If there is a \'[\', the nestedIn | ritaccc | NORMAL | 2020-09-10T21:31:40.066891+00:00 | 2020-09-10T21:31:40.066934+00:00 | 265 | false | 1 Everything will be pushed to stack, so no extra pointers or references needed (will get messy if there are many pointers)\n2 If there is a \'[\', the nestedInteger will be a list, so just add a list.\n3 if there is a num, it will be an integer, so get the list from stack, and add the integer to the stack\n4 if there is a \']\', add current list to previous list\n5 if there is a \',\', do nothing\n\n```\npublic NestedInteger deserialize(String s) {\n if (s == null) {\n return null;\n }\n if (s.charAt(0) != \'[\') {\n return new NestedInteger(Integer.parseInt(s));\n }\n char[] arr = s.toCharArray();\n int n = arr.length;\n \n Stack<NestedInteger> stack = new Stack<>();\n int i = 0;\n while (i < n) {\n if (arr[i] == \'[\') {\n stack.push(new NestedInteger());\n } else if (Character.isDigit(arr[i]) || arr[i] == \'-\') {\n int num = 0;\n int sign = 1;\n if (arr[i] == \'-\') {\n sign = -1;\n i++;\n }\n while (i < n && Character.isDigit(arr[i])) {\n num = num * 10 + arr[i] - \'0\';\n i++;\n }\n i--;\n stack.peek().getList().add(new NestedInteger(num * sign)); \n } else if (arr[i] == \']\') {\n NestedInteger ni = stack.pop();\n if (!stack.isEmpty()) {\n stack.peek().getList().add(ni);\n } else {\n return ni;\n }\n }\n i++;\n }\n \n return stack.pop();\n } | 2 | 0 | [] | 1 |
mini-parser | Swift: SIMPLE & SWEET, 100% | swift-simple-sweet-100-by-voxqhuy-nse0 | \nfunc deserialize(_ s: String) -> NestedInteger {\n\tif s.first != "[" {\n\t\treturn NestedInteger(Int(s))\n\t}\n\n\tvar stack = [NestedInteger]()\n\tvar resul | voxqhuy | NORMAL | 2020-08-21T22:31:22.304858+00:00 | 2020-08-21T22:31:22.304894+00:00 | 118 | false | ```\nfunc deserialize(_ s: String) -> NestedInteger {\n\tif s.first != "[" {\n\t\treturn NestedInteger(Int(s))\n\t}\n\n\tvar stack = [NestedInteger]()\n\tvar result = NestedInteger()\n\tstack.append(result)\n\tvar curInt = ""\n\n\tfor char in s.dropFirst() {\n\t\tif char == "[" {\n\t\t\tvar ni = NestedInteger()\n\t\t\tstack.last!.add(ni)\n\t\t\tstack.append(ni)\n\t\t} else if char == "," || char == "]" {\n\t\t\t// add the curInt to the last one\n\t\t\tif !curInt.isEmpty {\n\t\t\t\tstack.last!.add(NestedInteger(Int(curInt)))\n\t\t\t}\n\t\t\tif char == "]" {\n\t\t\t\tstack.popLast()!\n\t\t\t}\n\n\t\t\tcurInt = ""\n\t\t} else {\n\t\t\tcurInt += String(char)\n\t\t}\n\t}\n\n\treturn result\n} \n``` | 2 | 0 | ['Swift'] | 0 |
mini-parser | Very simple 7 line solution in java | very-simple-7-line-solution-in-java-by-r-iv4s | There are 2 cases\n1. list\n2. number\n\nFor the list case, call recursively.\n\n\npublic NestedInteger deserialize(String s) {\n\tNestedInteger ans = new Neste | rishirdua | NORMAL | 2019-04-23T07:39:30.692576+00:00 | 2019-04-23T07:39:30.692621+00:00 | 191 | false | There are 2 cases\n1. list\n2. number\n\nFor the list case, call recursively.\n\n```\npublic NestedInteger deserialize(String s) {\n\tNestedInteger ans = new NestedInteger();\n\tif (s.charAt(0) == \'[\') { // list\n\t\tArrays.stream(s.substring(1, s.length()-1).split(","))\n\t\t\t .forEach(a -> ans.add(deserialize(a)));\n\t} else { // number\n\t\tans.setInteger(Integer.parseInt(s));\n\t}\n\treturn ans;\n}\n``` | 2 | 0 | [] | 0 |
mini-parser | c++ stack 100%, がんばります! | c-stack-100-ganbarimasu-by-solaaoi-d3rt | \n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class Ne | solaaoi | NORMAL | 2018-09-14T18:06:10.510502+00:00 | 2018-09-14T18:06:10.510548+00:00 | 302 | false | ```\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n * public:\n * // Constructor initializes an empty nested list.\n * NestedInteger();\n *\n * // Constructor initializes a single integer.\n * NestedInteger(int value);\n *\n * // Return true if this NestedInteger holds a single integer, rather than a nested list.\n * bool isInteger() const;\n *\n * // Return the single integer that this NestedInteger holds, if it holds a single integer\n * // The result is undefined if this NestedInteger holds a nested list\n * int getInteger() const;\n *\n * // Set this NestedInteger to hold a single integer.\n * void setInteger(int value);\n *\n * // Set this NestedInteger to hold a nested list and adds a nested integer to it.\n * void add(const NestedInteger &ni);\n *\n * // Return the nested list that this NestedInteger holds, if it holds a nested list\n * // The result is undefined if this NestedInteger holds a single integer\n * const vector<NestedInteger> &getList() const;\n * };\n */\nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n int n = s.length();\n\n vector<pair<NestedInteger, bool>> stk;\n\n int i = 0;\n int num = 0;\n int sign = 1;\n while (i < n) {\n if (s[i] == \'[\') {\n stk.push_back(make_pair(NestedInteger(), true));\n ++i;\n } else if (s[i] == \'-\') { // [note]: it\'s possible the number is negative!!!\n sign = -1;\n ++i;\n } else if (s[i] >= \'0\' && s[i] <= \'9\') {\n num = 0;\n while (i < n && s[i] >= \'0\' && s[i] <= \'9\') {\n num = num * 10 + (s[i] - \'0\');\n ++i;\n }\n stk.push_back(make_pair(NestedInteger(sign * num), false));\n sign = 1;\n } else if (s[i] == \',\') {\n ++i;\n } else {\n vector<NestedInteger> vec;\n while (!stk.back().second) {\n vec.push_back(stk.back().first);\n stk.pop_back();\n }\n auto pr = stk.back();\n stk.pop_back();\n\n int nvec = vec.size();\n for (int j = nvec - 1; j >= 0; --j) {\n pr.first.add(vec[j]);\n }\n pr.second = false;\n stk.push_back(pr);\n ++i;\n }\n }\n\n return stk.back().first;\n }\n};\n\n``` | 2 | 0 | [] | 0 |
mini-parser | Java solution | java-solution-by-octoray-r03s | \npublic class Solution {\n\n\tpublic NestedInteger deserialize(String s) {\n\t\tint len = s.length();\n\t\tif (!s.startsWith("[")) {\n\t\t\tNestedInteger ni = | octoray | NORMAL | 2018-05-05T20:17:57.169672+00:00 | 2018-08-27T20:34:14.405369+00:00 | 479 | false | ```\npublic class Solution {\n\n\tpublic NestedInteger deserialize(String s) {\n\t\tint len = s.length();\n\t\tif (!s.startsWith("[")) {\n\t\t\tNestedInteger ni = new NestedInteger(Integer.parseInt(s));\n\t\t\treturn ni;\n\t\t}\n\t\tNestedInteger root = new NestedInteger();\n\t\tStack<NestedInteger> stack = new Stack<>();\n\t\tstack.push(root);\n\t\tfor (int i = 1; i < len - 1; i++) {\n\t\t\tchar c = s.charAt(i);\n\t\t\tif (c == \'[\') {\n\t\t\t\tNestedInteger ni = new NestedInteger();\n\t\t\t\tstack.peek().add(ni);\n\t\t\t\tstack.push(ni);\n\t\t\t} else if (c == \',\') {\n\t\t\t\tcontinue;\n\t\t\t} else if (c == \']\') {\n\t\t\t\tstack.pop();\n\t\t\t} else {\n\t\t\t\tint start = i;\n\t\t\t\twhile (i < len - 1 && s.charAt(i + 1) >= \'0\' && s.charAt(i + 1) <= \'9\') {\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tint end = i;\n\t\t\t\tstack.peek().add(new NestedInteger(Integer.parseInt(s.substring(start, end + 1))));\n\t\t\t}\n\t\t}\n\t\treturn stack.pop();\n\t}\n\n}\n``` | 2 | 0 | [] | 2 |
mini-parser | Share my simple JAVA solution with explanation | share-my-simple-java-solution-with-expla-ocvt | Basic idea is: \n1) when you see '[' you know you have to create a new NextedInteger object, but before that you have to store, if any, your current work into s | bbccyy1 | NORMAL | 2016-08-14T15:13:22.735000+00:00 | 2016-08-14T15:13:22.735000+00:00 | 797 | false | Basic idea is: \n1) when you see '[' you know you have to create a new NextedInteger object, but before that you have to store, if any, your current work into stack (we use stack structure to preserve the input order)\n2) when you see ']' you can close current work and add it to the first element in stack, then replace your current work with this NextedInteger that previously worked with.\n3) when you see a number (don't forget '-') you put it into a single valued NextedInteger object, add it to your current work.\n\nsome corner case: "324" v.s "[324]" --> Integer v.s single Valued NextedInteger object\n\n\n```\npublic class Solution {\n public NestedInteger deserialize(String s) {\n Stack<NestedInteger> stk = new Stack<>();\n Reader input = new Reader(s);\n NestedInteger cur = null;\n while(input.hasNext()){\n String next = input.next();\n if(next.equals("[")){\n if(cur!=null){\n stk.push(cur);\n }\n cur = new NestedInteger();\n }\n else if(next.equals("]")){\n if(!stk.isEmpty()){\n stk.peek().add(cur);\n cur = stk.pop();\n }\n }\n else{\n int val = Integer.valueOf(next);\n if(cur==null){\n cur = new NestedInteger(val);\n }\n else{\n cur.add(new NestedInteger(val));\n }\n }\n }\n return cur;\n }\n \n class Reader{ // a helper class that passes input string into useful elements\n String str;\n int p, len;\n public Reader(String s){\n str = s;\n p = 0;\n len = str.length();\n }\n public boolean hasNext(){\n return p<len;\n }\n public String next(){\n if(str.charAt(p)==',') p++;\n int s = p;\n while(p<len && (str.charAt(p)=='-' || Character.isDigit(str.charAt(p)))) p++;\n if(s!=p) return str.substring(s,p);\n return str.substring(s,++p);\n }\n }\n}\n``` | 2 | 0 | [] | 0 |
mini-parser | Extremely simple Python solution | extremely-simple-python-solution-by-peng-0imj | python\nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n return ev | pengge | NORMAL | 2016-08-25T12:36:20.375000+00:00 | 2016-08-25T12:36:20.375000+00:00 | 288 | false | ```python\nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n return eval(s)\n```\nThis code could pass the test cases. But I don't know whether this solution is legal or not. | 2 | 1 | [] | 0 |
mini-parser | C++ iterative solution | c-iterative-solution-by-soamaaazing-gmnp | Construct NestedInteger while parsing the string s:\n\n NestedInteger deserialize(string s) {\n stack<NestedInteger> st;\n int num = 0, sign = | soamaaazing | NORMAL | 2016-08-26T01:36:41.011000+00:00 | 2016-08-26T01:36:41.011000+00:00 | 486 | false | Construct NestedInteger while parsing the string s:\n```\n NestedInteger deserialize(string s) {\n stack<NestedInteger> st;\n int num = 0, sign = 1; \n bool numValid = false;\n \n for (int i = 0; i < s.length(); i++) {\n if (s[i] == '-') {\n sign = -1; \n } else if (isdigit(s[i])) {\n numValid = true;\n num = num * 10 + (s[i] - '0');\n } else if (s[i] == '[') {\n // start a new nested list as current active nested list\n st.push(NestedInteger()); \n } else { \n // meaning s[i] == ',' || s[i] == ']'\n // add the last interger into current active nested list, and clear num/sign\n if (numValid) { st.top().add(NestedInteger(sign * num)); }\n numValid = false; num = 0; sign = 1;\n \n // add current active nested list to its parent nested list if the parent exists\n if (s[i] == ']' && st.size() > 1) {\n auto temp = st.top(); st.pop();\n st.top().add(temp);\n }\n } \n }\n \n // if there's only one single integer, return it\n if (numValid) {\n return NestedInteger(sign * num);\n }\n // else return the nested list\n return st.top();\n }\n```\n\nA cleaner way with better decomposition:\n```\nclass Solution {\nprivate:\n string getNext(string& s, int& pos) { // get next element: '[', ']', number string\n if (pos < s.length() && s[pos] == ',') { pos++; } // skip ','\n if (pos < s.length() && (s[pos] == '[' || s[pos] == ']')) { return s.substr(pos++, 1); }\n int start = pos;\n if (pos < s.length() && s[pos] == '-') { pos++; } // include '-' in a number substring\n while (pos < s.length() && isdigit(s[pos])) { pos++; } // get the number substring\n return s.substr(start, pos - start);\n }\n \npublic:\n NestedInteger deserialize(string s) {\n stack<NestedInteger> st;\n \n for (int pos = 0; pos < s.length();) {\n string curStr = getNext(s, pos);\n \n if (curStr == "[") {\n st.push(NestedInteger()); // start a new nested list\n } else { // curStr may be either "]" or a number string\n NestedInteger item;\n if (curStr == "]") { item = st.top(); st.pop(); } // complete the last nested list / interger\n else { item = NestedInteger(stoi(curStr)); } // it's a number string\n \n if (st.size()) { st.top().add(item); } // merge it into previous nested list\n else { st.push(item); } // itself is the top parent nested list / integer\n }\n }\n \n return st.top();\n }\n};\n``` | 2 | 0 | [] | 0 |
mini-parser | my solution using formal grammar. long but elegant in my opinion... | my-solution-using-formal-grammar-long-bu-p5qj | \n/**\n * grammar for the context.\n * NestedInteger := Number | [InnerNestedIneger]\n * InnerNestedInteger := NestedInteger | InnerNestedInte | alvisjiang | NORMAL | 2016-08-28T13:23:24.458000+00:00 | 2016-08-28T13:23:24.458000+00:00 | 310 | false | ```\n/**\n * grammar for the context.\n * NestedInteger := Number | [InnerNestedIneger]\n * InnerNestedInteger := NestedInteger | InnerNestedInteger,NestedInteger\n * Number := -PositiveNumber | PositiveNumber\n * PositiveNumber := digit | digitPositiveNumber\n */\npublic class Solution {\n \n private int index;\n private int sLen;\n \n public NestedInteger deserialize(String s) {\n sLen = s.length();\n if (sLen == 0) {\n return new NestedInteger();\n }\n index = 0;\n return nestedInteger(s);\n }\n \n public NestedInteger nestedInteger(String s) {\n \n if (leftBracket(s)) {\n NestedInteger result = innerNestedInteger(s);\n rightBracket(s);\n return result;\n } else {\n return integer(s);\n }\n \n }\n \n public NestedInteger innerNestedInteger(String s) {\n NestedInteger result = new NestedInteger();\n do {\n NestedInteger subResult = nestedInteger(s);\n if (subResult != null) {\n result.add(subResult);\n }\n } while (comma(s));\n return result;\n }\n \n public boolean leftBracket(String s) {\n if (index >= sLen) {\n return false;\n }\n if (s.charAt(index) == '[') {\n index++;\n return true;\n } else\n return false;\n }\n \n public NestedInteger integer(String s) {\n int posOrNeg = negtiveSign(s) ? -1 : 1;\n \n int num = positiveInteger(s); \n if (num != -1) {\n num *= posOrNeg;\n return new NestedInteger(num);\n }\n \n return null;\n }\n \n public int positiveInteger(String s) {\n int num = 0;\n int digit = 0;\n boolean foundDigit = false;\n while (digit != -1) {\n digit = digit(s);\n if (digit > -1 && digit < 10) {\n foundDigit = true;\n num = num * 10 + digit;\n }\n }\n return foundDigit ? num : -1;\n }\n \n public boolean comma(String s) {\n if (index >= sLen) {\n return false;\n }\n if (s.charAt(index) == ',') {\n index++;\n return true;\n } else {\n return false;\n }\n }\n \n public int digit(String s) {\n if (index >= sLen) {\n return -1;\n }\n int result = s.charAt(index) - '0';\n if (result >= 0 && result <= 9) {\n index++;\n return result;\n } else {\n return -1;\n }\n }\n \n public boolean rightBracket(String s) {\n if (index >= sLen) {\n return false;\n }\n if (s.charAt(index) == ']') {\n index++;\n return true;\n } else {\n return false;\n }\n }\n \n public boolean negtiveSign(String s) {\n if (index >= sLen) {\n return false;\n }\n if (s.charAt(index) == '-') {\n index++;\n return true;\n } else {\n return false;\n }\n }\n}\n``` | 2 | 0 | [] | 1 |
mini-parser | Python recursive solution | python-recursive-solution-by-johnnydu-9064 | \nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n try:\n | johnnydu | NORMAL | 2016-10-12T01:06:09.934000+00:00 | 2016-10-12T01:06:09.934000+00:00 | 317 | false | ```\nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n try:\n return int(s)\n except:\n i, open_paren, result = 1, 0, []\n for j in range(1, len(s)-1):\n if s[j] == ',' and not open_paren:\n result.append(s[i:j])\n i = j+1\n elif s[j] == '[':\n open_paren += 1\n elif s[j] == ']':\n open_paren -= 1\n if i < len(s)-1:\n result.append(s[i:len(s)-1])\n \n for i in range(len(result)):\n result[i] = self.deserialize(result[i])\n \n return result\n \n``` | 2 | 0 | [] | 0 |
mini-parser | Java solution using StringTokenizer and Stack, easy and clear logic | java-solution-using-stringtokenizer-and-c31pc | \nimport java.util.StringTokenizer;\npublic class Solution {\n\n public NestedInteger deserialize(String s) {\n StringTokenizer tokenizer = new String | xamous | NORMAL | 2017-01-05T15:14:12.144000+00:00 | 2017-01-05T15:14:12.144000+00:00 | 528 | false | ```\nimport java.util.StringTokenizer;\npublic class Solution {\n\n public NestedInteger deserialize(String s) {\n StringTokenizer tokenizer = new StringTokenizer(s, "[],", true);\n\n Stack<NestedInteger> stack = new Stack<>();\n stack.push(new NestedInteger()); // a dummy list to simplify init\n\n while (tokenizer.hasMoreTokens()) {\n String token = tokenizer.nextToken();\n switch (token) {\n case "[":\n NestedInteger list = new NestedInteger();\n stack.peek().add(list);\n stack.push(list);\n break;\n case "]":\n stack.pop();\n break;\n case ",":\n break;\n default: // number\n NestedInteger num = new NestedInteger(Integer.parseInt(token));\n stack.peek().add(num);\n }\n }\n\n return stack.pop().getList().get(0);\n }\n\n}\n``` | 2 | 0 | [] | 1 |
mini-parser | Elegant Python one-pass solution, beats 93%, easy to understand | python-one-pass-solution-build-answer-ch-tckx | IntuitionRead string from left to right, char by char, remember context when necessary -- just like a normal human being.Complexity
Time complexity:O(n)
Space c | guozhenli | NORMAL | 2025-02-20T09:14:40.245662+00:00 | 2025-02-22T06:33:04.156116+00:00 | 205 | false | # Intuition
Read string from left to right, char by char, remember context when necessary -- just like a normal human being.
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(n)$$
# Code
```python3 []
class Solution:
def deserialize(self, s: str) -> NestedInteger:
context = None
item = None
stack = []
sign = 1
for token in s:
if token.isdigit():
if item is None:
item = NestedInteger()
item.setInteger(10*(item.getInteger() or 0) + sign * int(token))
elif token == '-':
sign = -1
elif token == '[':
stack.append(context)
context = NestedInteger()
item = None
elif token == ']':
if item is not None:
context.add(item)
item = context
context = stack.pop()
elif token == ',':
context.add(item)
item = None
sign = 1
return item
``` | 1 | 0 | ['Python3'] | 0 |
mini-parser | Recursion - Java O(N)|O(1) | recursion-java-ono1-by-wangcai20-4wzz | Intuition\n Describe your first thoughts on how to solve this problem. \nOne pass scan from left to right and chop at each , at root level:\n if chopped section | wangcai20 | NORMAL | 2024-10-23T16:20:27.658680+00:00 | 2024-10-23T16:21:04.310585+00:00 | 79 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne pass scan from left to right and chop at each `,` at root level:\n* if chopped section is number, add a `Integer` type of NestedInteger.\n* if chopped section is list, add a `List` type of NestedInteger.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public NestedInteger deserialize(String s) {\n if (Character.isDigit(s.charAt(0)) || s.charAt(0) == \'-\')\n return new NestedInteger(Integer.parseInt(s));\n else {\n String ss = s.substring(1, s.length() - 1) + ",";\n //System.out.println(ss);\n NestedInteger ni = new NestedInteger();\n for (int i = 0, cnt = 0, last = 0; i < ss.length(); i++) {\n if (ss.charAt(i) == \'[\')\n cnt++;\n if (ss.charAt(i) == \']\')\n cnt--;\n if (ss.charAt(i) == \',\' && cnt == 0) {\n //System.out.println(">>" + ss.substring(last, i) + "<<");\n if (last != i)\n ni.add(deserialize(ss.substring(last, i)));\n last = i + 1;\n }\n }\n return ni;\n }\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
mini-parser | C++ easy solution | c-easy-solution-by-chandleryeh-44rt | Intuition\nNested Solution with golbal counter\nwhen encounter \'[\', enter nested\nwhen encounter \']\', leave nested\n\n# Code\n\n/**\n * // This is the inter | chandleryeh | NORMAL | 2024-06-16T13:05:20.726888+00:00 | 2024-06-16T13:05:20.726916+00:00 | 350 | false | # Intuition\nNested Solution with golbal counter\nwhen encounter \'[\', enter nested\nwhen encounter \']\', leave nested\n\n# Code\n```\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n * public:\n * // Constructor initializes an empty nested list.\n * NestedInteger();\n *\n * // Constructor initializes a single integer.\n * NestedInteger(int value);\n *\n * // Return true if this NestedInteger holds a single integer, rather than a nested list.\n * bool isInteger() const;\n *\n * // Return the single integer that this NestedInteger holds, if it holds a single integer\n * // The result is undefined if this NestedInteger holds a nested list\n * int getInteger() const;\n *\n * // Set this NestedInteger to hold a single integer.\n * void setInteger(int value);\n *\n * // Set this NestedInteger to hold a nested list and adds a nested integer to it.\n * void add(const NestedInteger &ni);\n *\n * // Return the nested list that this NestedInteger holds, if it holds a nested list\n * // The result is undefined if this NestedInteger holds a single integer\n * const vector<NestedInteger> &getList() const;\n * };\n */\nclass Solution {\npublic:\n string s;\n int i;\n int n;\n NestedInteger helper()\n {\n NestedInteger ret;\n string t;\n for(;i<n; i++)\n {\n if(isdigit(s[i]) || s[i]==\'-\')\n {\n t+=s[i];\n }\n else if(s[i] == \',\')\n {\n if(!t.empty())\n {\n ret.add(NestedInteger(stoi(t)));\n t.clear();\n }\n }\n else if(s[i] == \'[\')\n {\n i++;\n ret.add(helper());\n \n }\n else if(s[i]==\']\')\n {\n if(!t.empty())\n {\n ret.add(NestedInteger(stoi(t)));\n t.clear();\n }\n break;\n }\n }\n\n return ret;\n\n }\n NestedInteger deserialize(string s) {\n if(s[0] != \'[\') return NestedInteger(stoi(s));\n\n this->s = s;\n n = s.size();\n i = 1;\n\n return helper();\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
mini-parser | Recursive parser | recursive-parser-by-vokasik-1xl4 | \nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n def parse():\n nonlocal i\n lst = NestedInteger()\n | vokasik | NORMAL | 2024-06-01T03:00:46.011416+00:00 | 2024-06-01T03:00:46.011442+00:00 | 370 | false | ```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n def parse():\n nonlocal i\n lst = NestedInteger()\n while i < len(s):\n prev = i\n while s[i] == \'-\' or s[i].isdigit():\n i += 1\n if prev != i:\n lst.add(NestedInteger(int(s[prev:i]))) # parse a number\n elif s[i] == \'[\':\n i += 1\n lst.add(parse()) # add a new list\n elif s[i] == \']\': # return processed list\n i += 1\n return lst\n else: # for now it\'s just \',\'\n i += 1\n return lst\n i = 1\n return parse() if s[0] == \'[\' else NestedInteger(int(s)) # parse a number or a list\n``` | 1 | 0 | ['Python', 'Python3'] | 0 |
mini-parser | MOST easy to understand coding | most-easy-to-understand-coding-by-dingoo-tdlg | Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n\n# Code\n\n/**\n * // This is the interface that allows for creating nested lists. | Dingoooooo | NORMAL | 2024-03-26T10:46:53.460635+00:00 | 2024-03-26T10:46:53.460662+00:00 | 145 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Code\n```\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * public interface NestedInteger {\n * // Constructor initializes an empty nested list.\n * public NestedInteger();\n *\n * // Constructor initializes a single integer.\n * public NestedInteger(int value);\n *\n * // @return true if this NestedInteger holds a single integer, rather than a nested list.\n * public boolean isInteger();\n *\n * // @return the single integer that this NestedInteger holds, if it holds a single integer\n * // Return null if this NestedInteger holds a nested list\n * public Integer getInteger();\n *\n * // Set this NestedInteger to hold a single integer.\n * public void setInteger(int value);\n *\n * // Set this NestedInteger to hold a nested list and adds a nested integer to it.\n * public void add(NestedInteger ni);\n *\n * // @return the nested list that this NestedInteger holds, if it holds a nested list\n * // Return empty list if this NestedInteger holds a single integer\n * public List<NestedInteger> getList();\n * }\n */\nclass Solution {\n public NestedInteger deserialize(String s) {\n //basic case 1\n if (s.equals("[]")) {\n return new NestedInteger();\n }\n //basic case 2\n if (Character.isDigit(s.charAt(0)) || s.charAt(0) == \'-\') {\n int value = Integer.valueOf(s);\n return new NestedInteger(value);\n }\n //it is a nest list, we try to split it with \',\'\n s = s.substring(1, s.length() - 1);\n NestedInteger ans = new NestedInteger();\n int l = 0;\n int count = 0;\n //we only care about the first level\n for (int r = 0; r < s.length(); r++) {\n char ch = s.charAt(r);\n if (ch == \'[\') {\n count++;\n } else if (ch == \']\') {\n count--;\n } else if (ch == \',\' && count == 0) {\n System.out.println("*");\n NestedInteger nest = deserialize(s.substring(l, r));\n ans.add(nest);\n l = r + 1;\n }\n }\n //add the last part\n NestedInteger nest = deserialize(s.substring(l, s.length()));\n ans.add(nest);\n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
mini-parser | go 1.21, clean code | go-121-clean-code-by-colix-ukee | \nfunc deserialize(s string) *NestedInteger {\n\tstack := []NestedInteger{{}}\n\tfor i := 0; i < len(s); i++ {\n\t\tswitch s[i] {\n\t\tcase \'0\', \'1\', \'2\', | colix | NORMAL | 2024-03-09T09:14:26.939079+00:00 | 2024-03-09T09:14:26.939104+00:00 | 37 | false | ```\nfunc deserialize(s string) *NestedInteger {\n\tstack := []NestedInteger{{}}\n\tfor i := 0; i < len(s); i++ {\n\t\tswitch s[i] {\n\t\tcase \'0\', \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \'-\':\n\t\t\tj := i + 1\n\t\t\tfor ; j < len(s) && unicode.IsDigit(rune(s[j])); j++ {}\n\t\t\tinteger, _ := strconv.Atoi(s[i:j])\n\t\t\tnestedInteger := NestedInteger{}\n\t\t\tnestedInteger.SetInteger(integer)\n\t\t\tstack[len(stack)-1].Add(nestedInteger)\n\t\t\ti = j - 1\n\t\tcase \'[\':\n\t\t\tstack = append(stack, NestedInteger{})\n\t\tcase \']\':\n\t\t\tnestedInteger := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-1]\n\t\t\tstack[len(stack)-1].Add(nestedInteger)\n\t\t}\n\t}\n\treturn stack[len(stack)-1].GetList()[0]\n}\n``` | 1 | 0 | ['Go'] | 0 |
mini-parser | Kotlin, 100% on runtime. | kotlin-100-on-runtime-by-lev5-0b7i | Intuition\nUse simple recursion to consume input since it maps organically to the NestedInteger data structure. Also note that [] are guaranteed to be matching | lev5 | NORMAL | 2024-02-13T19:58:36.950877+00:00 | 2024-02-13T19:58:36.950912+00:00 | 192 | false | # Intuition\nUse simple recursion to consume input since it maps organically to the `NestedInteger` data structure. Also note that `[]` are guaranteed to be matching.\n\nAdditionally, we try to avoid string manipulation which may result in new objects created. Also prefer raw parsing.\n\n# Approach\nMake recursive function which takes in position - `i: Int` into string with 2 base cases\n1. This is an integer, so we parse until we hit end of string or non digit and then return new `NestedInteger` which contains just the number and the position at which we stopped parsing.\n2. This is a list, so we make\n 1. Create a new NestedInteger representing list.\n 2. Make recursive calls until we hit a `]`. Each recursive call\'s index is called with previous recursive\'s call returned index + 1.\n 3. Return new NestedInteger representing list and the index at which we stopped parsing.\n\n# Complexity\n- Time complexity:\nO(N) where N is input string length.\n\n- Space complexity:\nO(M) where M is the level of deepest nested list. \n\n# Code\n```\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n * // Constructor initializes an empty nested list.\n * constructor()\n *\n * // Constructor initializes a single integer.\n * constructor(value: Int)\n *\n * // @return true if this NestedInteger holds a single integer, rather than a nested list.\n * fun isInteger(): Boolean\n *\n * // @return the single integer that this NestedInteger holds, if it holds a single integer\n * // Return null if this NestedInteger holds a nested list\n * fun getInteger(): Int?\n *\n * // Set this NestedInteger to hold a single integer.\n * fun setInteger(value: Int): Unit\n *\n * // Set this NestedInteger to hold a nested list and adds a nested integer to it.\n * fun add(ni: NestedInteger): Unit\n *\n * // @return the nested list that this NestedInteger holds, if it holds a nested list\n * // Return null if this NestedInteger holds a single integer\n * fun getList(): List<NestedInteger>?\n * }\n */\nclass Solution {\n fun deserialize(s: String): NestedInteger {\n fun dfs(i: Int): Pair<NestedInteger, Int> {\n // println("$i, ${s[i]}")\n if (s.isEmpty()) return NestedInteger() to 0\n var k = i\n while (k < s.length && (s[k] == \',\' || s[k] == \']\')) k += 1\n if (s[k].isDigit() || s[k] == \'-\') {\n var j = k + 1\n while (j < s.length && s[j].isDigit()) j += 1\n return NestedInteger(s.substring(k, j).toInt()) to j\n } else {\n var j = k + 1\n val nl = NestedInteger()\n while (j < s.length && s[j] != \']\') {\n val c = dfs(j)\n j = c.second\n nl.add(c.first) \n // println("j: $j, ${s[j]}")\n }\n return nl to j + 1\n }\n }\n\n return dfs(0).first\n }\n}\n``` | 1 | 0 | ['Kotlin'] | 0 |
mini-parser | DFS + IMPLEMENT DELIMTER FUNCTION || JAVA || 10 MS | dfs-implement-delimter-function-java-10-ylacc | Code\n\nclass Solution {\n public NestedInteger deserialize(String s) {\n if(isInteger(s)) {\n return s.isEmpty() ? new NestedInteger() : n | youssef1998 | NORMAL | 2023-06-20T20:37:46.842873+00:00 | 2023-06-20T20:37:46.842889+00:00 | 552 | false | # Code\n```\nclass Solution {\n public NestedInteger deserialize(String s) {\n if(isInteger(s)) {\n return s.isEmpty() ? new NestedInteger() : new NestedInteger(getIntegerValue(s));\n }\n s = removeBrackets(s);\n NestedInteger list = new NestedInteger();\n for (String child: delimitedStr(s)) {\n if(child.isEmpty()) continue;\n list.add(deserialize(child));\n }\n return list;\n }\n\n private boolean isInteger(String str) {\n return !str.contains(",") && !str.startsWith("[") && !str.endsWith("]");\n }\n\n private int getIntegerValue(String s) {\n if(s.startsWith("-")) return - Integer.parseInt(s.substring(1));\n return Integer.parseInt(s);\n }\n\n private String removeBrackets(String s) {\n return s.substring(1, s.length()-1);\n }\n\n private List<String> delimitedStr(String str) {\n if(!str.contains(",")) return List.of(str);\n List<String> delimited = new ArrayList<>();\n int numBrackets = 0;\n StringBuilder sb = new StringBuilder();\n for (Character c: str.toCharArray()) {\n if(!sb.isEmpty() && numBrackets == 0 && c == \',\') {\n delimited.add(sb.toString());\n sb = new StringBuilder();\n } else if(!sb.isEmpty() && c == \']\' && numBrackets-1 == 0) {\n sb.append(c);\n numBrackets = 0;\n delimited.add(sb.toString());\n sb = new StringBuilder();\n } else {\n if (sb.isEmpty() && c == \',\') continue; \n sb.append(c);\n if(c == \'[\') numBrackets++;\n if(c == \']\') numBrackets--;\n }\n }\n if(!sb.isEmpty()) delimited.add(sb.toString());\n return delimited;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
mini-parser | Java | Recursive solution | java-recursive-solution-by-somesh9827-3xny | NestedInteger can contain Integer or List so handled them sepretly. \n\nclass Solution {\n int c = 0;\n public NestedInteger deserialize(String s) {\n | somesh9827 | NORMAL | 2022-04-30T12:16:26.213783+00:00 | 2022-04-30T12:16:26.213812+00:00 | 158 | false | NestedInteger can contain Integer or List so handled them sepretly. \n```\nclass Solution {\n int c = 0;\n public NestedInteger deserialize(String s) {\n char[] chars = s.toCharArray();\n return deserialize(chars);\n }\n \n NestedInteger deserialize(char[] chars) {\n if(chars[c] == \'[\') {\n c++;\n NestedInteger parent = new NestedInteger(); \n \n while(c < chars.length && chars[c] != \']\') {\n if(chars[c] == \',\') {c++; continue;}\n parent.add(deserialize(chars));\n }\n c++;\n return parent;\n \n }\n else {\n StringBuilder sb = new StringBuilder();\n while(c < chars.length && ((chars[c] >= \'0\' && chars[c] <=\'9\') || (chars[c] == \'-\'))) {\n sb.append(chars[c]);\n c++; \n } \n return new NestedInteger(Integer.valueOf(sb.toString()));\n }\n \n \n }\n \n}\n``` | 1 | 0 | [] | 0 |
mini-parser | Java Recursive Solution | java-recursive-solution-by-kojo-ko88 | \nclass Solution {\n public NestedInteger deserialize(String s) {\n if(s.charAt(0) != \'[\') return new NestedInteger(Integer.parseInt(s));\n \ | kojo | NORMAL | 2022-03-17T10:53:07.101683+00:00 | 2022-03-17T10:53:07.101711+00:00 | 149 | false | ```\nclass Solution {\n public NestedInteger deserialize(String s) {\n if(s.charAt(0) != \'[\') return new NestedInteger(Integer.parseInt(s));\n \n NestedInteger res = new NestedInteger();\n int left = 1, right = s.length() - 1;\n while(left < right){\n int start = left;\n if(s.charAt(left) == \',\'){\n left++;\n continue;\n }else if(s.charAt(left) != \'[\'){\n while(s.charAt(left) != \',\' && left < right) left++;\n }else {\n left++;\n int count = 1;\n while(count != 0 && left < right){\n char c = s.charAt(left++);\n count += (c == \'[\') ? 1 : (c == \']\' ? -1 : 0);\n }\n }\n NestedInteger inner = deserialize(s.substring(start, left));\n res.add(inner);\n }\n return res; \n }\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | Elegant Python One Pass Solution (using stack) | elegant-python-one-pass-solution-using-s-ozay | \nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n stack = []\n integerStr = \'\'\n \n for c in s:\n | RG97 | NORMAL | 2021-12-20T23:38:09.680690+00:00 | 2021-12-20T23:38:09.680719+00:00 | 382 | false | ```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n stack = []\n integerStr = \'\'\n \n for c in s:\n if c == \'[\':\n stack.append(NestedInteger())\n elif c == \']\':\n if len(integerStr)>0:\n stack[-1].add(NestedInteger(int(integerStr)))\n integerStr = \'\'\n poppedList = stack.pop()\n if len(stack)==0:\n return poppedList\n stack[-1].add(poppedList)\n elif c == \',\':\n if len(integerStr)>0:\n stack[-1].add(NestedInteger(int(integerStr)))\n integerStr = \'\'\n else:\n integerStr += c\n \n return NestedInteger(int(s))\n``` | 1 | 0 | ['Stack', 'Python3'] | 0 |
mini-parser | Python solution using stack | python-solution-using-stack-by-aaman007-mq56 | Using Stack:\n\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if s.find(\'[\') == -1:\n return NestedInteger(int(s))\ | aaman007 | NORMAL | 2021-11-24T15:24:10.758747+00:00 | 2021-11-24T15:24:10.758777+00:00 | 362 | false | Using Stack:\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if s.find(\'[\') == -1:\n return NestedInteger(int(s))\n \n stack = []\n sign = 1\n num = None\n \n for ch in s:\n if ch == \'-\':\n sign = -1\n elif ch == \',\':\n if num is not None:\n stack[-1].add(NestedInteger(sign * num))\n sign = 1\n num = None\n elif ch == \'[\':\n stack.append(NestedInteger())\n elif ch == \']\':\n if num is not None:\n stack[-1].add(NestedInteger(sign * num))\n sign = 1\n num = None\n _list = stack.pop()\n if stack:\n stack[-1].add(_list)\n else:\n return _list\n else:\n num = num * 10 + int(ch) if num else int(ch)\n```\n**Side note:** This is assuming the given string is serialized by us and will always be valid. If it can be invalid we will need to handle edge cases.\n\nUsing json module (which I don\'t think is the intended solution, but might come in handy in development):\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n \n def build(data):\n if isinstance(data, int):\n return NestedInteger(data)\n \n result = NestedInteger()\n for val in data:\n result.add(build(val))\n \n return result\n \n return build(json.loads(s))\n``` | 1 | 0 | ['Stack', 'Python'] | 0 |
mini-parser | Java easy stack solution | java-easy-stack-solution-by-codingpianop-rxwi | \nclass Solution {\n public NestedInteger deserialize(String s) {\n // sb for digit value\n StringBuilder sb = new StringBuilder();\n \n | codingpianoplayer | NORMAL | 2021-11-17T20:24:46.981855+00:00 | 2021-11-17T20:24:46.981893+00:00 | 146 | false | ```\nclass Solution {\n public NestedInteger deserialize(String s) {\n // sb for digit value\n StringBuilder sb = new StringBuilder();\n \n Stack<NestedInteger> stack = new Stack<>();\n \n NestedInteger lastList = null;\n \n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n \n if (c == \'[\') {\n NestedInteger list = new NestedInteger();\n stack.push(list);\n } else if (isDigit(c)) {\n sb.append(c);\n } else if (c == \',\') {\n if (sb.length() > 0) {\n stack.peek().add(new NestedInteger(toInt(sb.toString())));\n sb = new StringBuilder();\n }\n } else if (c == \']\') {\n lastList = stack.pop();\n if (sb.length() > 0) lastList.add(new NestedInteger(toInt(sb.toString())));\n sb = new StringBuilder();\n if (!stack.isEmpty()) {\n stack.peek().add(lastList);\n }\n }\n }\n \n if (lastList == null) {\n return new NestedInteger(toInt(sb.toString()));\n } else {\n return lastList;\n }\n }\n \n private boolean isDigit(char c) {\n if ((c >= \'0\') && (c <= \'9\')) {\n return true;\n }\n \n return c == \'-\';\n }\n \n private int toInt(String s) {\n return Integer.valueOf(s).intValue();\n }\n}\n``` | 1 | 0 | [] | 1 |
mini-parser | [c++] recursive solution O(N) | c-recursive-solution-on-by-nraptis-f2vn | \nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n int index = 0;\n return deserialize(s, index);\n }\n \n NestedIn | nraptis | NORMAL | 2021-10-19T18:33:26.048612+00:00 | 2021-10-19T18:33:26.048651+00:00 | 166 | false | ```\nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n int index = 0;\n return deserialize(s, index);\n }\n \n NestedInteger deserialize(string s, int &index) {\n NestedInteger result;\n if (s[index] == \'[\') {\n parseList(s, index, &result);\n } else {\n result.setInteger(parseNum(s, index));\n }\n return result;\n }\n \n void parseList(string s, int &index, NestedInteger *parent) {\n index++;\n while (s[index] != \']\') {\n if (s[index] == \',\') {\n index++;\n } else if (s[index] == \'[\') {\n NestedInteger n;\n parseList(s, index, &n);\n parent->add(n);\n } else {\n NestedInteger n;\n n.setInteger(parseNum(s, index));\n parent->add(n);\n }\n }\n index++;\n }\n \n int parseNum(string s, int &index) {\n bool negative = false;\n int value = 0;\n if (s[index] == \'-\') {\n negative = true;\n index++;\n }\n int result = 0;\n while (isNum(s[index])) {\n result *= 10;\n result += (s[index] - \'0\');\n index += 1;\n }\n if (negative) {\n result = -result;\n }\n return result;\n }\n \n bool isNum(char c) {\n if (c >= \'0\' && c <= \'9\') { return true; }\n return false;\n }\n};\n```\n\nCoo Coo | 1 | 0 | [] | 0 |
mini-parser | Faster than 100%, nice~ | faster-than-100-nice-by-370203400-em6p | javascript\nvar deserialize = function(s) {\n if(!s) return null\n s = JSON.parse(s)\n let n = new NestedInteger()\n function fn(nt, s) {\n i | 370203400 | NORMAL | 2021-10-06T11:08:16.184853+00:00 | 2023-01-08T10:40:50.235823+00:00 | 251 | false | ```javascript\nvar deserialize = function(s) {\n if(!s) return null\n s = JSON.parse(s)\n let n = new NestedInteger()\n function fn(nt, s) {\n if(Array.isArray(s)) {\n let a = new NestedInteger()\n for(let item of s) {\n let ret = fn(a, item)\n a.add(ret)\n }\n return a\n }\n return new NestedInteger(s)\n }\n\n let ret = fn(n, s)\n\n return ret\n};\n```\n\nmodified at 2023-01-08\n```js\nvar deserialize = function(s) {\n if(!s) return null\n s = JSON.parse(s)\n function fn(s) {\n if(Array.isArray(s)) {\n let a = new NestedInteger()\n for(let item of s) {\n let ret = fn(item)\n a.add(ret)\n }\n return a\n }\n return new NestedInteger(s)\n }\n\n let ret = fn(s)\n\n return ret\n};\n``` | 1 | 0 | ['JavaScript'] | 1 |
mini-parser | C# no stack easy solution | c-no-stack-easy-solution-by-luanshixia-6big | csharp\npublic NestedInteger Deserialize(string s) {\n\tif (!s.Contains(\'[\')) {\n\t\treturn new NestedInteger(Convert.ToInt32(s));\n\t}\n\tvar list = new Nest | luanshixia | NORMAL | 2021-08-11T23:01:38.533359+00:00 | 2021-08-11T23:01:38.533428+00:00 | 68 | false | ```csharp\npublic NestedInteger Deserialize(string s) {\n\tif (!s.Contains(\'[\')) {\n\t\treturn new NestedInteger(Convert.ToInt32(s));\n\t}\n\tvar list = new NestedInteger();\n\ts = s.Substring(1, s.Length - 2);\n\tvar i = 0;\n\tvar j = 0;\n\tvar bracketCounter = 0;\n\twhile (i < s.Length) {\n\t\tif (bracketCounter == 0) {\n\t\t\tj = i;\n\t\t}\n\t\twhile (i < s.Length && s[i] != \',\') {\n\t\t\tif (s[i] == \'[\') {\n\t\t\t\tbracketCounter++;\n\t\t\t} else if (s[i] == \']\') {\n\t\t\t\tbracketCounter--;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\tif (bracketCounter == 0) {\n\t\t\tlist.Add(Deserialize(s.Substring(j, i - j)));\n\t\t}\n\t\ti++;\n\t}\n\treturn list;\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | Go Easy | go-easy-by-oliver2010-4p1f | \nfunc deserialize(s string) *NestedInteger {\n stk:=[]*NestedInteger{}\n curr:=""\n for _,v:=range s{\n if v==\'[\'{\n //init\n | Oliver2010 | NORMAL | 2021-08-06T18:21:26.580581+00:00 | 2021-08-06T18:21:26.580624+00:00 | 85 | false | ```\nfunc deserialize(s string) *NestedInteger {\n stk:=[]*NestedInteger{}\n curr:=""\n for _,v:=range s{\n if v==\'[\'{\n //init\n stk=append(stk,&NestedInteger{})\n }else if v==\']\'{\n if curr!=""{\n stk[len(stk)-1].Add(*buildNI(curr))\n curr=""\n }\n if len(stk)>1{//tricky\n back:=stk[len(stk)-1]\n stk=stk[:len(stk)-1]\n stk[len(stk)-1].Add(*back)\n }\n \n }else if v==\',\'{\n if curr==""{\n continue\n }\n stk[len(stk)-1].Add(*buildNI(curr))\n curr=""\n }else{\n curr+=string(v)\n }\n }\n if curr!=""{\n stk=append(stk,buildNI(curr))\n }\n return stk[len(stk)-1]\n}\n\nfunc buildNI(val string) *NestedInteger{\n temp:=&NestedInteger{}\n v,_:=strconv.Atoi(val)\n temp.SetInteger(v)\n return temp\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | Python beat 100% runtime and 99.48% memory recursive solution | python-beat-100-runtime-and-9948-memory-33fc9 | \ndef deserialize(self, s: str) -> NestedInteger:\n\n\n\n\tdef helper(new_str, idx, is_list=False):\n\n\t\tstart = idx\n\n\t\tif is_list:\n\t\t\tresult = list() | ashwin_karthik | NORMAL | 2021-07-06T16:27:57.570738+00:00 | 2021-07-06T16:27:57.570781+00:00 | 99 | false | ```\ndef deserialize(self, s: str) -> NestedInteger:\n\n\n\n\tdef helper(new_str, idx, is_list=False):\n\n\t\tstart = idx\n\n\t\tif is_list:\n\t\t\tresult = list()\n\t\telse:\n\t\t\tresult = NestedInteger()\n\n\t\tfor cur_idx, ch in enumerate(new_str[idx:]):\n\t\t\tif ch == ",":\n\t\t\t\tni = NestedInteger(new_str[start:idx+cur_idx])\n\n\t\t\t\tif is_list:\n\t\t\t\t\tresult.append(ni)\n\t\t\t\telse:\n\t\t\t\t\treturn ni\n\n\t\t\t\tstart = idx + cur_idx + 1\n\n\t\t\telif ch == \'[\':\n\t\t\t\tresult.append(helper(new_str, idx + cur_idx + 1, is_list=True))\n\n\t\t\telif ch == \']\':\n\t\t\t\tbreak\n\n\t\treturn NestedInteger(new_str)\n\n\tif s[0] == "[":\n\t\treturn helper(s, 1, is_list=True)\n\telse:\n\t\treturn helper(s, 0, is_list=False)\n``` | 1 | 0 | [] | 0 |
mini-parser | C++ O(n) Stack Solution | c-on-stack-solution-by-mhdareeb-oqty | \nclass Solution {\npublic:\n NestedInteger deserialize(string s)\n {\n NestedInteger ans;\n stack<NestedInteger>st;\n int i=0;\n | mhdareeb | NORMAL | 2021-05-24T14:10:27.411824+00:00 | 2021-05-24T14:10:27.411871+00:00 | 153 | false | ```\nclass Solution {\npublic:\n NestedInteger deserialize(string s)\n {\n NestedInteger ans;\n stack<NestedInteger>st;\n int i=0;\n if(s[i]!=\'[\')//just one integer\n {\n ans=NestedInteger(stoi(s));\n return ans;\n }\n while(i<s.size())\n {\n if(s[i]==\',\')//ignore\n {\n i++;\n continue;\n }\n if(s[i]==\'[\')//start new NestedInteger\n {\n NestedInteger temp=NestedInteger();\n st.push(temp);\n }\n else if(s[i]==\'-\' || isdigit(s[i]))//number begins\n {\n int sign=1;\n if(s[i]==\'-\')\n {\n sign=-1;\n i++;\n }\n int num=0;\n while(i<s.size() && isdigit(s[i]))//form number till \',\' or \']\' is found\n {\n num=(num*10)+(s[i]-\'0\');\n i++;\n }\n i--;\n num=num*sign;\n st.top().add(num);//push it to current NestedInteger\n }\n else//s[i]==\']\'\n {\n NestedInteger top = st.top();//this will be added to next current NestedInteger, or become final answer\n st.pop();\n if(st.empty())\n ans=top;\n else\n st.top().add(top);\n }\n i++;\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
mini-parser | 93% :: Python (Eval | Recursion) | 93-python-eval-recursion-by-tuhinnn_py-xnuf | \n# """\n# This is the interface that allows for creating nested lists.\n# You should not implement it, or speculate about its implementation\n# """\n#class Nes | tuhinnn_py | NORMAL | 2021-05-16T15:21:27.437214+00:00 | 2021-05-16T15:21:27.437259+00:00 | 122 | false | ```\n# """\n# This is the interface that allows for creating nested lists.\n# You should not implement it, or speculate about its implementation\n# """\n#class NestedInteger:\n# def __init__(self, value=None):\n# """\n# If value is not specified, initializes an empty list.\n# Otherwise initializes a single integer equal to value.\n# """\n#\n# def isInteger(self):\n# """\n# @return True if this NestedInteger holds a single integer, rather than a nested list.\n# :rtype bool\n# """\n#\n# def add(self, elem):\n# """\n# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.\n# :rtype void\n# """\n#\n# def setInteger(self, value):\n# """\n# Set this NestedInteger to hold a single integer equal to value.\n# :rtype void\n# """\n#\n# def getInteger(self):\n# """\n# @return the single integer that this NestedInteger holds, if it holds a single integer\n# Return None if this NestedInteger holds a nested list\n# :rtype int\n# """\n#\n# def getList(self):\n# """\n# @return the nested list that this NestedInteger holds, if it holds a nested list\n# Return None if this NestedInteger holds a single integer\n# :rtype List[NestedInteger]\n# """\n\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n s = eval(s)\n def getNestedInteger(nums):\n if type(nums) == int:\n return NestedInteger(nums)\n ans = NestedInteger()\n for num in nums:\n ans.add(getNestedInteger(num))\n return ans \n return getNestedInteger(s)\n``` | 1 | 0 | [] | 0 |
mini-parser | python one pass stack solution | python-one-pass-stack-solution-by-bravep-m8w4 | this problem is not clear and kind of broken.\nthe only useful api of the class is __init__ and add, others only make this problem confusing. Took me 20 min eff | bravephoenix | NORMAL | 2021-04-10T01:27:09.353410+00:00 | 2021-04-10T01:30:03.984200+00:00 | 173 | false | this problem is not clear and kind of broken.\nthe only useful api of the class is ```__init__``` and ```add```, others only make this problem confusing. Took me 20 min efforts to guess what the question wants and only 10 min to solve.\nNotice that you have to use ```add(NestedInteger(#num))``` instead of using ```add(#num)``` directly. \n\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n stack = []\n num = ""\n for x in s:\n if x == \'[\':\n if not (not num or not stack):\n stack[-1].add(int(num))\n num = ""\n stack.append(NestedInteger())\n elif x == \']\':\n tmp = stack.pop()\n if num:\n tmp.add(NestedInteger(int(num)))\n num = ""\n if not stack:\n return tmp\n else:\n stack[-1].add(tmp)\n elif x == \',\':\n if num:\n stack[-1].add(NestedInteger(int(num)))\n num = ""\n else:\n num += x\n return NestedInteger(int(num))\n``` | 1 | 0 | [] | 1 |
mini-parser | C++ recursive soln | c-recursive-soln-by-hmqhuange-7jzw | \nRecursive solution, similar to https://leetcode.com/problems/decode-string/\n```\nNestedInteger deserialize(string s) {\n if (s.empty()) return NestedI | hmqhuange | NORMAL | 2021-03-21T06:20:42.999036+00:00 | 2021-03-21T06:20:42.999080+00:00 | 333 | false | \nRecursive solution, similar to https://leetcode.com/problems/decode-string/\n```\nNestedInteger deserialize(string s) {\n if (s.empty()) return NestedInteger();\n if (s[0] != \'[\') return NestedInteger(stoi(s));\n if (s.size() <= 2) return NestedInteger();\n int pos = 1;\n return parse(s, pos);\n }\n \n NestedInteger parse(string s, int& i) {\n int intVal = 0;\n NestedInteger res;\n char sign = \'+\';\n for (; i < s.size(); i++) {\n if (s[i] == \'-\') sign = \'-\';\n else if (isdigit(s[i])) {\n while (isdigit(s[i])) {\n intVal = intVal * 10 + (s[i++] - \'0\');\n }\n res.add(sign == \'+\' ? intVal : -intVal);\n intVal = 0;\n sign = \'+\';\n i--;\n }\n else if (s[i] == \'[\') {\n res.add(parse(s, ++i));\n } \n else if (s[i] == \']\') {\n return res;\n }\n }\n return res;\n }\n | 1 | 0 | ['Recursion', 'C'] | 0 |
mini-parser | [Java] Recursion, Like N-ary Tree deserializtion | java-recursion-like-n-ary-tree-deseriali-nxyj | \n public NestedInteger deserialize(String s) {\n if(s.charAt(0) == \'[\') {\n NestedInteger root = new NestedInteger();\n s = s | cxhcxh | NORMAL | 2021-02-19T17:05:32.916819+00:00 | 2021-02-19T17:05:32.916862+00:00 | 146 | false | ```\n public NestedInteger deserialize(String s) {\n if(s.charAt(0) == \'[\') {\n NestedInteger root = new NestedInteger();\n s = s.substring(1, s.length() - 1); //remove \'[]\'\n \n while(!s.equals("")) {\n if(s.charAt(0) != \'[\') {\n int index = s.indexOf(",");\n if(index == -1) { // \',\' not found\n root.add(deserialize(s));\n s = "";\n } else { //found \',\'\n root.add(deserialize(s.substring(0, index)));\n s = s.substring(index + 1);\n }\n } else {\n int i = 0, count = 0;\n while(i < s.length()) {\n if(s.charAt(i) == \'[\') count++;\n if(s.charAt(i) == \']\') count--;\n if(count == 0) break;\n i++;\n }\n root.add(deserialize(s.substring(0, ++i)));\n if(i == s.length()) s = ""; // if it\'s end\n else s = s.substring(i + 1); // it\'s not end, it has \',\'\n }\n }\n\n return root;\n } else {\n return new NestedInteger(Integer.parseInt(s));\n }\n }\n``` | 1 | 0 | [] | 0 |
mini-parser | Java using recursion: Time O(N) and Space O(1 except output objects) | java-using-recursion-time-on-and-space-o-1o0h | \nclass Solution {\n \n private int index = 0;\n \n public NestedInteger deserialize(String s) {\n NestedInteger ni = new NestedInteger();\n | solver1318 | NORMAL | 2021-01-09T23:28:47.177326+00:00 | 2021-01-09T23:28:47.177368+00:00 | 141 | false | ```\nclass Solution {\n \n private int index = 0;\n \n public NestedInteger deserialize(String s) {\n NestedInteger ni = new NestedInteger();\n \n if (s.charAt(index) == \'[\') {\n // ni will be list object\n index++;\n } else {\n // Return simple integer object\n return getIntegerObject(s);\n }\n \n while (index < s.length()) {\n if (s.charAt(index) == \'[\') {\n ni.add(deserialize(s));\n } else if (s.charAt(index) != \']\') {\n ni.add(getIntegerObject(s));\n }\n if (s.charAt(index) == \']\') {\n // If we encounter ], then stop return current list object\n index++;\n break;\n } \n index++;\n }\n return ni;\n }\n \n private NestedInteger getIntegerObject(String s) {\n StringBuilder sb = new StringBuilder();\n while (index < s.length()) {\n // Parse num strings\n if (s.charAt(index) == \',\' || s.charAt(index) == \']\') {\n break;\n }\n sb.append(s.charAt(index));\n index++;\n }\n // Index will stop at \',\' or \']\'\n return new NestedInteger(Integer.parseInt(sb.toString()));\n }\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | [Java] Short clean code using stack | java-short-clean-code-using-stack-by-shk-1hi6 | -, 0-9 means start of an integer so parse it.\n[ means a new NestedInteger begins so push the current one into stack.\n] means current NestedInteger ends so pop | shk10 | NORMAL | 2020-12-26T22:13:19.343877+00:00 | 2020-12-26T22:13:19.343918+00:00 | 396 | false | ```-, 0-9``` means start of an integer so parse it.\n```[``` means a new NestedInteger begins so push the current one into stack.\n```]``` means current NestedInteger ends so pop from stack to get its parent. Also, add current to parent list. (Alternatively, we could have done this while creating the new NestedInteger.)\n```,``` means do nothing.\n```\npublic NestedInteger deserialize(String s) {\n Deque<NestedInteger> stack = new ArrayDeque<>();\n NestedInteger cur = new NestedInteger();\n char[] c = s.toCharArray();\n for(int i = 0; i < c.length; i++) {\n if(c[i] == \'-\' || c[i] >= \'0\' && c[i] <= \'9\') {\n boolean sign = c[i] == \'-\';\n int val = sign ? 0 : c[i] - \'0\';\n while(i+1 < c.length && c[i+1] >= \'0\' && c[i+1] <= \'9\') val = val * 10 + c[++i] - \'0\';\n cur.add(new NestedInteger(sign ? -val : val));\n } else if(c[i] == \'[\') {\n stack.push(cur);\n cur = new NestedInteger();\n } else if(c[i] == \']\') {\n stack.peek().add(cur);\n cur = stack.pop();\n }\n }\n return cur.getList().iterator().next();\n}\n``` | 1 | 1 | ['Stack', 'Java'] | 0 |
mini-parser | 100%/100% Python3, Brute force | 100100-python3-brute-force-by-awong05-or4c | This is likely unintended, but I am surprised there aren\'t more posts about how broken this problem is.\n\n\nclass Solution:\n def deserialize(self, s: str) | awong05 | NORMAL | 2020-09-23T21:17:32.257411+00:00 | 2020-09-23T21:17:32.257455+00:00 | 121 | false | This is likely unintended, but I am surprised there aren\'t more posts about how broken this problem is.\n\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n return NestedInteger(s)\n``` | 1 | 1 | [] | 1 |
mini-parser | Detailed Solution to an Ambiguous question. [No wonder why so many dislikes] | detailed-solution-to-an-ambiguous-questi-cv4b | Hi guys this is an ambigious question and no good explaination is available anywhere, here i\'ve heavily commented the code so that the reader can understand, a | geekyanurag | NORMAL | 2020-09-01T16:55:53.539157+00:00 | 2020-09-01T17:02:07.178398+00:00 | 78 | false | Hi guys this is an ambigious question and no good explaination is available anywhere, here i\'ve heavily commented the code so that the reader can understand, also if you have doubts please comment!\ni\'ll create a youtube video on this ans share the link here [];\n\n```\n//NI -- > Nested Integer\nclass Solution {\n \n Stack<NestedInteger> stack = new Stack<>();\n NestedInteger ans = new NestedInteger();\n \n //for keeping at what index of string are we\n int index;\n \n /*since the string can also contain negative integers, we will have to keep track of sign */\n \n int sign;\n\n //function provided by leetcode\n public NestedInteger deserialize(String s) {\n /* \n We will start traversing form the 1 index of the string, that is where \n a number would begin with.\n if a string begins with a number that means there is only one integer in\n it , becuase if there was a list ,it would begin with [\n */\n index = 1;\n sign = 1; \n \n //checking if the list contains only one integer\n if(s.charAt(0)!=\'[\'){\n return new NestedInteger(Integer.parseInt(s));\n }\n \n myDeserialize(s);\n return ans;\n }\n \n \n /*Each time a call to myDerialize is called it means a nesting has taken place*/\n \n public void myDeserialize(String s){\n //just a safety check\n if(index >=s.length())return ;\n \n //initialize a new NestedInteger for this call\n NestedInteger newNI = new NestedInteger();\n \n /* if the stack is emtpy then we just push the current NI if not then\n we add the newly created NI to the last NI.\n [IMP] : The top of stack contains the current list always\n */\n if(stack.size()!=0)stack.peek().add(newNI);\n else{\n /*first time we create a NI , that is our answer, so we store it\'s refrence*/\n \n ans = newNI;\n }\n //pushing current NI to top of the stack\n stack.push(newNI);\n \n //iterate till our string is over\n while(index<s.length()){\n char ch = s.charAt(index);\n /*\n if at some time [ is encountered a nesting is detected hence recursive call \n */\n if(ch==\'[\'){\n index++;\n myDeserialize(s);\n }\n \n /* \n If ] is encountered that means current NI\'s work is over , pop it from stack\n */\n else if (ch ==\']\'){\n index++;\n stack.pop();\n }\n //maintain the sign of the integer\n else if (ch ==\'-\'){\n sign = -1;\n index++;\n }\n //if comma , do nothing , just move forward \n else if(ch==\',\'){\n index++;\n }\n /*\n if a digit is encountered, then trverse till there are digits\n form a number , convert it into an integer and push the number\n in the current NI\n */\n else{\n //getting the current integer\n int endIndex = index;\n while(Character.isDigit(s.charAt(++endIndex)));\n String number_string = s.substring(index , endIndex);\n int number = sign*Integer.parseInt(number_string);\n stack.peek().add(new NestedInteger(number));\n sign = 1;\n index = endIndex;\n }\n \n }\n \n }\n \n}\n\n\n```\nPlease upvote if it helped you :)\nThankyou | 1 | 0 | [] | 0 |
mini-parser | [Java] - Clean & Easy to Read | java-clean-easy-to-read-by-philip2207-qh5i | java\npublic static class StringIterator {\n \n\tprivate final String s;\n\tprivate int i;\n\n\tStringIterator(String s) {\n\t\tthis.s = s;\n\t\tthis.i = | philip2207 | NORMAL | 2020-07-28T12:51:59.416636+00:00 | 2020-07-28T12:51:59.416669+00:00 | 431 | false | ```java\npublic static class StringIterator {\n \n\tprivate final String s;\n\tprivate int i;\n\n\tStringIterator(String s) {\n\t\tthis.s = s;\n\t\tthis.i = 0;\n\t}\n\n\tpublic boolean hasNext() {\n\t\treturn i < s.length();\n\t}\n\n\tpublic char next() {\n\t\tchar c = s.charAt(i);\n\t\ti++;\n\t\treturn c;\n\t}\n\n\tpublic char peek() {\n\t\treturn s.charAt(i);\n\t}\n}\n\npublic NestedInteger deserialize(String s) {\n\treturn deserialize(new StringIterator(s)); \n}\n\npublic NestedInteger deserialize(StringIterator iter) {\n\tchar c = iter.peek();\n\n\tif (Character.isDigit(c) || c == \'-\') {\n\t\treturn new NestedInteger(parseNumber(iter));\n\t}\n\n\tNestedInteger nestedIntegerList = new NestedInteger();\n\t// If it doesn\'t start with a number, it should start with a \'[\'\n\titer.next();\n\twhile (iter.hasNext()) {\n\t\tc = iter.peek();\n\t\tswitch (c) {\n\t\t\tcase \']\':\n\t\t\t\titer.next();\n\t\t\t\treturn nestedIntegerList;\n\t\t\tcase \',\':\n\t\t\t\titer.next();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tnestedIntegerList.add(deserialize(iter));\n\t\t}\n\t}\n\treturn nestedIntegerList;\n}\n\nprivate int parseNumber(StringIterator iter) {\n\tboolean isNegative = iter.peek() == \'-\';\n\tif (isNegative) {\n\t\titer.next();\n\t}\n\tint value = 0;\n\n\twhile (iter.hasNext() && Character.isDigit(iter.peek())) {\n\t\tvalue *= 10;\n\t\tvalue += (iter.next() - \'0\') * (isNegative ? -1 : 1);\n\t}\n\treturn value;\n}\n``` | 1 | 0 | ['Java'] | 0 |
mini-parser | Simple Java solution | simple-java-solution-by-irapohlf-t3gi | This seemed complicated at first, but as I implemented, I found that it is not that difficult.\nOn the otherhand, as I said, I couldn\'t figure out the solution | irapohlf | NORMAL | 2020-07-11T06:19:09.413552+00:00 | 2020-07-11T06:19:09.413586+00:00 | 176 | false | This seemed complicated at first, but as I implemented, I found that it is not that difficult.\nOn the otherhand, as I said, I couldn\'t figure out the solution very clearly before start to code, so I might fail if this was my coding question.\n\n```\nclass Solution { \n private boolean isDigit(char ch) {\n return ch >= \'0\' && ch <= \'9\';\n }\n \n public NestedInteger deserialize(String s) {\n if (!s.startsWith("[")) {\n return new NestedInteger(Integer.valueOf(s));\n }\n \n Stack<NestedInteger> stk = new Stack<>();\n \n char[] chs = s.toCharArray();\n int ret = 0;\n int sign = 1;\n NestedInteger ni;\n for (int i = 0; i < chs.length; i++) {\n switch (chs[i]) {\n case \'[\':\n ni = new NestedInteger();\n if (stk.size() > 0) {\n stk.peek().add(ni);\n }\n stk.push(ni);\n break;\n case \']\':\n ni = stk.pop();\n if (isDigit(chs[i-1])) {\n ni.add(new NestedInteger(ret * sign));\n sign = 1;\n ret = 0;\n }\n if (i == chs.length-1) {\n return ni;\n }\n break;\n case \'-\':\n sign = -1;\n break;\n case \',\':\n if (isDigit(chs[i-1])) {\n stk.peek().add(new NestedInteger(ret * sign));\n sign = 1;\n ret = 0;\n }\n break;\n default:\n ret = ret * 10 + (int) (chs[i]-\'0\');\n }\n }\n \n return null;\n }\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | C++ recursive slution | c-recursive-slution-by-carpdm-r4c2 | C++\nNestedInteger deserialize(string s) {\n \n if (s.size() == 0) return NestedInteger();\n if (s[0] != \'[\') return NestedInteger(stoi(s | carpdm | NORMAL | 2020-05-23T12:21:39.775727+00:00 | 2020-05-23T12:22:20.408073+00:00 | 135 | false | ```C++\nNestedInteger deserialize(string s) {\n \n if (s.size() == 0) return NestedInteger();\n if (s[0] != \'[\') return NestedInteger(stoi(s));\n NestedInteger res;\n // comma split\n int cnt = 0, last = 1;\n for (int i=1; i<s.size()-1; i++) {\n if (s[i] == \'[\') cnt += 1;\n else if (s[i] == \']\') cnt -= 1; \n else if (s[i] == \',\' && cnt == 0) {\n string seg = s.substr(last, i - last);\n res.add(deserialize(seg));\n last = i + 1;\n }\n }\n \n if (s.size()-1-last > 0) {\n string seg = s.substr(last, s.size()-1-last);\n res.add(deserialize(seg));\n }\n return res;\n }\n``` | 1 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.