3[abb2[a]]2[b]ee > aaabbabbabbbbee
背景知識 array, defaultdict
理解問題 repeat次數[要repeat的字]
思路視覺化 1 2 3 4 5 6 7 8 9 10 3[abb2[a]]2[b]ee > 3[abb]2[b]ee, ret = [aa] 3[abb]2[b]ee > 2[b]ee, ret = [aa] [abbabbabb] 2[b]ee > ee, ret = [aa] [abbabbabb] [bb] ee > , ret = [aa] [abbabbabb] [bb] [ee] join, , ret = [aaabbabbabbbbee] 判斷數字次數加入dict, 遇到]處理 {2:a, 3:abb,2:b} 再 數字*次數 再補剩下ee
443. String Compression 394. Decode String
Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 // compression class Solution { public int compress(char[] chars) { int ans = 0, i = 0; while(i < chars.length){ char curr = chars[i]; int count= 0; while(i < chars.length && chars[i] == curr){ i++; count++; } chars[ans++] = curr; if(count != 1){ for(char c: Integer.toString(count).toCharArray()){ chars[ans++] = c; } } } return ans; } // decompression public String decodeString(String s) { Stack<Character> stack = new Stack<>(); for(char c : s.toCharArray()){ if(c != ']') stack.push(c); //push everything but ] else { // word StringBuilder sb = new StringBuilder(); while(!stack.isEmpty() && Character.isLetter(stack.peek())) sb.insert(0, stack.pop()); String sub = sb.toString(); //this is the string contained in [ ] stack.pop(); //Discard '[' // repeat times sb.setLength(0); // clean while(!stack.isEmpty() && Character.isDigit(stack.peek())) sb.insert(0, stack.pop()); int count = Integer.valueOf(sb.toString()); //repeat word while(count > 0){ for(char ch : sub.toCharArray()) stack.push(ch); count--; } } } // the rest StringBuilder ret = new StringBuilder(); while(!stack.isEmpty()) ret.insert(0, stack.pop()); return ret.toString(); } }
Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 from collections import defaultdict s = "3[abb2[a]]2[b]ee" # aaabbabbabbbbee temp = defaultdict(list) # repeat:word {2:a, 3:abb,2:b} ret,repeat = [], 0 if len(s) == 0: print('') for c in s: if c.isdigit(): repeat = int(c) elif c.isalpha(): temp[repeat].append(c) elif c == ']': if len(temp)!= 0: pair = temp.popitem() ret += ''.join(pair[1]*pair[0]) # the rest while len(temp)!=0: pair = temp.popitem() ret+=pair[1] print(''.join(ret))
複雜度分析 TC: O(c+remain) SC: O(n)